I have an 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?
To append to an object with JavaScript, we can use the spread operator. let alerts = { 1: { app: "helloworld", message: "message" }, 2: { app: "helloagain", message: "another message" }, }; alerts = { ... alerts, alertNo: 2, }; to spread the existing properties of alerts into a new object with ... .
Object. assign({},objectname,{property: value}); In the example, we have used the assign () method to add a new element to an existing object. For that, we used an empty target place and are creating a new object so it does not change the existing object values.
In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve. push() function: The array push() function adds one or more values to the end of the array and returns the new length.
With ES2017 you could 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))
Here's one more because why not ~ meet 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'].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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With