Mona Lisa Mona Lisa - 25 days ago 7
JSON Question

How do you perform `push` on a JavaScript object?

What I am trying to achieve is use

push()
on a JavaScript object, that looks like so:

var apps = {
app1:
[
"ci-extension",
"Unnamed",
"<h1>Hello world!</h1>"
],
app2:
[
"ci-extension",
"Another one!",
"Cool!"
]
}


The goal is to add a third key "demo" to the object and then push another three lines to it.
So after all the pushing, the object should look like this:

var apps = {
app1:
[
"ci-extension",
"Unnamed",
"<h1>Hello world!</h1>"
],
app2:
[
"ci-extension",
"Another one!",
"Cool!"
],
demo:
[
"ci-google",
"My demo app!",
"Some content"
]
}


What I tried?



I tried the following piece of code
Object.keys(apps).push("demo");
(if this makes any sense). As an output, I just got 3 and the key "demo" was not added to the object.

And then to add items into demo I tried using this tiny piece of code
Object.keys(apps)["demo"].push("blah blah blah...");
, but it totally did not work.


My brain and thoughts got obfuscated. Any help would be highly appreciated and very welcome. Thanks in advance!

Answer Source

You don't need to push() here, that's for adding to an exising array. You just want to add a key. The easiest way is like this:

apps.demo = [ "ci-google", "My demo app!", "Some content" ];

Or, equivalently

apps["demo"] = [ "ci-google", "My demo app!", "Some content" ];

The reason your code doesn't work is because Object.keys( apps ) creates you a new array containing all the keys in the apps object, but doing stuff to that array doesn't do anything to the actual apps object - you're just editing your new array. What you need to do is change the apps object directly (as I've shown above).