Skip to content

JSON stringify array of objects | Example code

  • by

Simply use JSON stringify() method to JSON stringify the array of objects in JavaScript.

JSON stringify array of objects

Simple example code stringify given objects in the array.

<!DOCTYPE html>
<html>
<body>

  <script>
   var cheese_array = [
   {
    name: "Chedder",
    age: "34",
    smelly: true
  },
  {
    name: "Brie",
    age: "4",
    smelly: false
  },
  {
    name: "Blue Stilton",
    age: "13",
    smelly: true
  }
  ];

  var res = JSON.stringify(cheese_array);

  console.log(typeof(res))

  console.log(JSON.stringify(cheese_array))
</script>

</body>
</html>

Output:

JSON stringify array of objects

JSON stringify array of objects with property

For example stringify an array of objects with extra properties.

const data = [{foo: "1", bar: "2"}, {foo: "2", bar:"3"}];
data.extra = ["a", "b"];
JSON.stringify( {...data} );

// "{"0":{"foo":"1","bar":"2"},"1":{"foo":"2","bar":"3"},"extra":["a","b"]}"

Stringifying an object with nested arrays of objects in Javascript

Just assign the object you need stringifying to a variable and pass that to JSON.stringify():

<script>
   var myNewObject = {key1:true, key2:17, key3: [
    {k1: 10, k2:true, k3: "test" },
    {k1: 11, k2:true, k3: "testing" },
    {k1: false, k2:42, k3: "foo" },
    ]}; 

    var stringifiedObject = JSON.stringify(myNewObject);
    console.log(stringifiedObject);     
</script>

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

Leave a Reply

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