Categories
JavaScript Answers

How to add a new array element to a JSON object with JavaScript?

Spread the love

Sometimes, we want to add a new array element to a JSON object with JavaScript.

In this article, we’ll look at how to add a new array element to a JSON object with JavaScript.

How to add a new array element to a JSON object with JavaScript?

To add a new array element to a JSON object with JavaScript, we parse the JSON string into an object, add the item to the array in the object, and the convert the object back to a JSON string.

For instance, we write

let jsonStr =
  '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

const obj = JSON.parse(jsonStr);
obj["theTeam"].push({ teamId: "4", status: "pending" });
jsonStr = JSON.stringify(obj);

to call JSON.parse to parse jsonStr into an object.

Then we call push to push a new entry into the obj["theTeam"] array.

Finally we call JSON.stringify to convert obj back into a JSON string.

Conclusion

To add a new array element to a JSON object with JavaScript, we parse the JSON string into an object, add the item to the array in the object, and the convert the object back to a JSON string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *