Adding to a JS object that is not an array?

I have an object that looks something like this:

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

What is read in my javascript with a call to $ .getJSON.

So, I have a JS response object that contains all this data.

I need to add elements such that the "records" expand as follows:

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

I tried

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

But this does not work (I suppose because nothing is an array)

Can someone provide an alternative method?

+5
source share
6 answers

reply['entries'].push({"Bar": 0}) does not work, because entries not of type Array , but simply Object .

Use reply['entries']["Bar"] or reply.entries.Bar . See the demo version below:

 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); 
+3
source

With ES2017 you can use:

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

Note: this will not mutate the original source object, but instead will return a new one (usually this is good).

+5
source

Here is another one, because why not come across 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); 
+4
source

it becomes an object, so just add what you want: -

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

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

or reply.entries["Foo"] = 0

+2
source

To insert new entries into a JSON object, you can try something like this:

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

Say that you have a key and values ​​in someproperty and somevalue , you can simply insert them as:

 reply.entries[someproperty] = somevalue 
+1
source

Here is an alternative method:

 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; 
+1
source

Source: https://habr.com/ru/post/1258118/


All Articles