追加到一个不是数组的JS对象?

我有一个像这样的对象

{ "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0 } } 

用$ .getJSON调用读入我的javascript

所以我有JS对象“回复”,其中包含所有这些数据。

我需要附加项目,使“条目”扩展如下:

 { "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0, "Bar": 30, "Baz": 4 } } 

我努力了

 reply['entries'].push({"Bar": 0}); 

但这是行不通的(我认为,因为没有一个数组

有人可以提供一种替代方法吗?

       

网上收集的解决方案 "追加到一个不是数组的JS对象?"

reply['entries'].push({"Bar": 0})不起作用,因为entries不是Arraytypes的,而只是一个普通的Object

使用reply['entries']["Bar"]reply.entries.Bar 。 看下面的演示:

 var reply = { "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0, "Bar": 30, "Baz": 4 } } reply['entries']["Bar"] = 0; console.log(reply); 

有了ES2017,你可以使用:

 const input = ( { _id: 'DEADBEEF' , _rev: '2-FEEDME' , name: 'Jimmy Strawson' , link: 'placeholder.txt' , entries: ( { Foo: 0 } ) } ) const output = ( { ...input , entries: ( { ...input.entries , Bar: 30 , Baz: 4 } ) } ) console.info(JSON.stringify(output, null, 2)) 

这里还有一个,因为为什么不符合Object.assign

 let reply = {"_id":"DEADBEEF","_rev":"2-FEEDME","name":"Jimmy Strawson","link":"placeholder.txt","entries":{"Foo":0}}; Object.assign(reply.entries, { Bar: 30, Baz: 4, 'Bar Baz': 0 }); console.log('reply =', reply); 

它成为一个对象,所以只需添加你想要的:

 reply.entries.Foo = 0 reply.entries.Bar = 30 reply.entries.Baz = 4 

reply["entries"]["Foo"] = 0

reply.entries["Foo"] = 0

为了向JSON对象中插入新条目,可以尝试如下所示:

object["someproperty"] = somevalue;object.someproperty = somevalue;

假设你已经获得了someproperty属性和somevalue值的variables中的键和值,可以简单地将它们插入为:

 reply.entries[someproperty] = somevalue 

这是另一种方法:

 reply = { "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0 } } reply.entries.Bar=30; reply.entries.Baz=4; reply["entries"]["Bar"]=30; reply["entries"]["Baz"]=4;