Add a Key Value Pair to an array of objects in javascript?

徘徊边缘 提交于 2019-12-03 11:16:11

You can simply add properties ("fields") on the fly.

Try

myarray[0].Address = "123 Some St.";

or

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

along with a single value like

myarray[0].address = "your address";

Even you can add nested property on the fly as below:

myarray[0].address = { presentAddress: "my present address..." };

and can get the value as: myarray[0].address.presentAddress;

thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!