Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

javascript - 如何动态创建字典和添加键值对?(How to create dictionary and add key–value pairs dynamically?)

From post:

(从帖子:)

Sending a JSON array to be received as a Dictionary<string,string>

(发送要作为Dictionary <string,string>接收的JSON数组)

I'm trying to do this same thing as that post.

(我正在尝试做同样的事情。)

The only issue is that I don't know what the keys and the values are upfront.

(唯一的问题是我不知道密钥和值是什么。)

So I need to be able to dynamically add the key and value pairs and I don't know how to do that.

(所以我需要能够动态添加键和值对,我不知道该怎么做。)

Does anyone know how to create that object and add key value pairs dynamically?

(有谁知道如何创建该对象并动态添加键值对?)

I've tried:

(我试过了:)

var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";

But that doesn't work.

(但这不起作用。)

  ask by KenEucker translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var dict = []; // create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// repeat this last part as needed to add more key/value pairs

Basically, you're creating an object literal with 2 properties (called key and value ) and inserting it (using push() ) into the array.

(基本上,您正在创建一个具有2个属性(称为keyvalue )的对象文字,并将其插入(使用push() )到数组中。)


Edit: So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS object literal (aka map, aka hash, aka dictionary).

(编辑:所以差不多5年后,这个答案正在下降,因为它没有创建一个“正常”的JS对象文字(又名地图,又名哈希,又名字典)。)
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals , each with key and value properties.

(然而 ,可以创建OP要求的结构(和其在连接到其他问题示出),这是对象常量 ,每个阵列 keyvalue的属性。)

Don't ask me why that structure was required, but it's the one that was asked for.

(不要问我为什么需要这种结构,但这是被要求的结构。)

But, but, if what you want in a plain JS object - and not the structure OP asked for - see tcll's answer , though the bracket notation is a bit cumbersome if you just have simple keys that are valid JS names.

(但是,但是,如果你想要一个简单的JS对象 - 而不是 OP要求的结构 - 请参阅tcll的答案 ,尽管括号表示法有点麻烦,如果你只有简单的键是有效的JS名称。)

You can just do this:

(你可以这样做:)

// object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

Or use regular dot-notation to set properties after creating an object:

(或者在创建对象后使用常规点符号设置属性:)

// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that.

(如果您有包含空格的键,特殊字符或类似的东西,您确实需要括号表示法。)

Eg:

(例如:)

var dict = {};

// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// but this will
dict["some invalid key (for multiple reasons)"] = "value1";

You also want bracket notation if your keys are dynamic:

(如果您的键是动态的,您还需要括号表示法:)

dict[firstName + " " + lastName] = "some value";

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key.

(请注意,键(属性名称)始终是字符串,非字符串值在用作键时将强制转换为字符串。)

Eg a Date object gets converted to its string representation:

(例如, Date对象被转换为其字符串表示形式:)

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]" which doesn't make for a non-unique key.

(但请注意,这并不一定“只是工作”,因为许多对象将具有类似"[object Object]"的字符串表示形式,这不会产生非唯一键。)

So be wary of something like:

(所以要警惕:)

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

Despite objA and objB being completely different and unique elements, they both have the same basic string representation: "[object Object]" .

(尽管objAobjB是完全不同且独特的元素,但它们都具有相同的基本字符串表示: "[object Object]" 。)

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation.

(Date不是这样的原因是Date原型有一个自定义的toString方法,它覆盖了默认的字符串表示。)

And you can do the same:

(你也可以这样做:)

// a simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of toString .)

((注意,由于上面使用了一个随机数,名称冲突仍然可以很容易地发生。它只是为了说明toString的实现。))

So when trying to use objects as keys, JS will use the object's own toString implementation, if any, or use the default string representation.

(因此,当尝试使用对象作为键时,JS将使用对象自己的toString实现(如果有),或使用默认字符串表示。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...