How To Add JSON Object To Existing JSON Array In JavaScript | Code

Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects.

arryObj.push(jsonObj);

Add JSON object to existing JSON array in JavaScript

Simple example code pushes the object to Json Array.

<!DOCTYPE html> <html> <body> <script type="text/javascript"> favorites = [{ "artist" : "Mike king", "song_name" : "Mild Songs" }]; var myObj = { "artist" : "Johny steve", "song_name" : "Rock Songs" }; favorites.push(myObj); console.log(favorites); </script> </body> </html>

Output:

How to add JSON object to existing JSON array in JavaScript

How to append an array to existing JSON JavaScript?

Answer: You have to create an object to add properties:

var myobj = {name: "Julia", birthdate: "xxxx"}; myobj.movies = []; myobj.movies.push({title: "movie1", rating: 5}); myobj.movies.push({title: "movie2", rating: 3});

How to push JSON object into an array using JavaScript?

Answer: If there is a single object and you want to push the whole object into an array then you do simply push the object.

var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}; var data = []; data.push(feed); console.log(data);

If you have multiple objects then do iterate the object.

var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}; var data = []; for(var i in my_json) { data.push(my_json[i]); } console.log(data);

Do comment if you have any doubts or suggestions on this JS JSON topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Share this:

  • Facebook
  • WhatsApp
  • LinkedIn
  • More
  • X
  • Print
  • Reddit
  • Tumblr
  • Pinterest
  • Pocket
  • Telegram
  • Email

Related

Tag » Add Element Json Array Javascript