How to add an array element to JSON object in JavaScript.

From time to time we need to manipulate JSON data by adding new elements into it. A JSON object is typically more difficult to directly edit as its normally in a string format.

So, how can you add an array element into a JSON Object in JavaScript?

This is done by using the JavaScript native methods .parse()and .stringify()

We want to do this following:

  • Parse the JSON object to create a native JavaScript Object
  • Push new array element into the object using .push()
  • Use stringify() to convert it back to its original format.

Let’s take the following JSON string data as an example:

'{"characters":[{"name":"Tommy Vercetti","location":"Vice City"},{"name":"Carl Johnson","location":"Grove Street"},{"name":"Niko Bellic","location":"Liberty City"}]}'

We have a list of notorious GTA characters in our JSON. Let’s say we want to add one more character:

{"name":"Ken Rosenberg","location":"Vice City"}

First, we need to parse our original JSON data

const obj = JSON.parse(data);

Then we want to add our new character into the parsed object:

obj["characters"].push({ name: "Ken Rosenberg", location: "Vice City" });

With the new character added, our JSON object now looks like this:

{
   "characters":[
      {
         "name":"Tommy Vercetti",
         "location":"Vice City"
      },
      {
         "name":"Carl Johnson",
         "location":"Grove Street"
      },
      {
         "name":"Niko Bellic",
         "location":"Liberty City"
      },
      {
         "name":"Ken Rosenberg",
         "location":"Vice City"
      }
   ]
}

Finally, we want to flip the data variable back into its original stringified JSON format:

data = JSON.stringify(obj);

And there you have it. Remember, that JSON is just a different type of notation so its always available to be transformed back into a proper JavaScript object for data manipulation.

Proudly published with Gatsby