Hubert S. Cumberdale Hubert S. Cumberdale - 1 month ago 7
Javascript Question

Appending to a JS object that is not an array?

I have a JSON object that looks something like this

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


Which is read into my javascript with a $.getJSON call.

So I have the JS object "reply" that holds all this data.

I need to append items such that "entries" becomes extended as follows:

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


I have tried

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


But that does not work (I presume because nothing is an array)

Can someone provide an alternative method?

Answer

reply['entries'].push({"Bar": 0}) does not work as entries is not of type Array but just a plain Object.

Use reply['entries']["Bar"] or reply.entries.Bar. See demo 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);

Comments