如何创建字典并动态添加键值对? [英] How to create dictionary and add key–value pairs dynamically?

查看:54
本文介绍了如何创建字典并动态添加键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自帖子:

发送 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?

我试过了:

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

但这不起作用.

推荐答案

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

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

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

所以差不多 5 年后,这个答案被否决了,因为它没有创建一个正常"的 JS 对象文字(又名地图,又名哈希,又名字典).
然而,它创建了 OP 要求的结构(并且在链接到的另一个问题中说明了这一点),它是一个对象文字数组,每个都有 keyvalue 属性.不要问我为什么需要这种结构,但它是被要求的结构.

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).
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. Don't ask me why that structure was required, but it's the one that was asked for.

但是,但是,如果您在普通 JS 对象中想要什么 - 而 不是 OP 要求的结构 - 请参阅 tcll 的答案,但如果您只有有效 JS 名称的简单键,则括号表示法有点麻烦.你可以这样做:

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. 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. E.g:

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";

请注意,键(属性名称)始终是字符串,非字符串值在用作键时将被强制为字符串.例如.Date 对象被转换为其字符串表示:

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g. a Date object gets converted to its string representation:

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

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

但是请注意,这不一定只是有效",因为许多对象将具有像 "[object Object]" 这样的字符串表示形式,它不会产生非唯一键.所以要警惕类似的事情:

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. 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" }

尽管 objAobjB 是完全不同且唯一的元素,但它们都具有相同的基本字符串表示形式:"[object Object]".

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

Date 行为不像这样的原因是 Date 原型有一个自定义的 toString 方法,它覆盖了默认的字符串表示.你也可以这样做:

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation. 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"
//    }

(注意,由于上面使用了一个随机数,名字冲突还是很容易发生的.这里只是为了说明一个toString的实现.)

(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.)

所以当尝试使用对象作为键时,JS 会使用对象自己的 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.

这篇关于如何创建字典并动态添加键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆