How To Add A New Array Element To A JSON Object With JavaScript?

Skip to the content Close Menu
  • HTML
  • CSS
  • JavaScript
  • Python
  • Contact
  • About the Site
  • About the Author
Labrador retriever puppy walking on green grass
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.

Related Posts

  • How to add a new key value pair in existing JSON object using JavaScript?

    Sometimes, we want to add a new key value pair in existing JSON object using…

  • How to convert a JavaScript object to array?

    Sometimes, we want to convert a JavaScript object to array. In this article, we'll look…

  • How to create JSON object dynamically via JavaScript?

    Sometimes, we want to create JSON object dynamically via JavaScript. In this article, we'll look…

By John Au-Yeung

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

View Archive How to check if character is number with JavaScript? How to implement regions/code collapse in JavaScript?

Leave a Reply Cancel reply

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

Comment *

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

Current ye@r * Leave this field empty

Tag » Add Element Json Array Javascript