将键值对添加到javascript中的对象数组吗? [英] Add a Key Value Pair to an array of objects in javascript?
问题描述
如果我有这样的数组:
var myarray = [];
myarray.push({
"Name": 'Adam',
"Age": 33
});
myarray.push({
"Name": 'Emily',
"Age": 32
});
这给了我一个数组,我可以在其中提取myarray[0].Name
这样的值,这将给我亚当".
This gives me an array where I can pull out values like myarray[0].Name
which would give me "Adam".
但是,在构建此数组之后,如何在位置[0]的数组中添加值为"somewhere street"的地址"字段,以便该对象在位置0的字段现在为Name
,Age
和Address
具有相应的值?
However, after this array is built, how can I add an "address" field with a value of "somewhere street" into the array at position [0], so that my fields in that object at position zero are now Name
, Age
, and Address
with corresponding values?
我一直在想splice()
,但是找不到使用对象的示例,只是带有简单数组的示例.
I was thinking splice()
somehow but couldn't find an example using objects, just examples with simple arrays.
推荐答案
您可以简单地动态添加属性(字段").
You can simply add properties ("fields") on the fly.
尝试
myarray[0].Address = "123 Some St.";
或
myarray[0]["Address"] = "123 Some St.";
var myarray = [];
myarray.push({
"Name": 'Adam',
"Age": 33
});
myarray.push({
"Name": 'Emily',
"Age": 32
});
myarray[0]["Address"] = "123 Some St.";
console.log( JSON.stringify( myarray, null, 2 ) );
这篇关于将键值对添加到javascript中的对象数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!