Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stringify an array of objects?

I have created an array of objects that needs to be stored and kept for another page.

The array of objects is similar to this:

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

But when I JSON.stringify() it, it doesn't stringify the objects, only the array. So I end up with and array that looks like this:

[object Object], [object Object], [object Object]

So how do you stringify these objects in this array.


EDIT: This array of objects is then passed to an on click function similar to this:

$("#a-button").click(function() {
  var cheese_arr_stringify = JSON.stringify(cheese_array);
  sessionStorage.cheeseArray = cheese_arr_stringify;
  if(sessionStorage.cheeseArray) {
    window.location.href = "../";
  }
 });

So pretty much, its sets cheese_arr_stringify to a stringified version of the array of objects. Then it sets this stringified code to a session key. Following this, once it has been set cheeseArray it send it up one directory.


EDIT 2: This is an image of the session key after being stringified. In this case, foodItems is the same as cheeseArray

Session Storage


EDIT 3: @Rayon asked for a fiddle so he could have a look, I made it up and it had worked. The problem was - I feel so stupid now - that I was calling the array instead of the stringified var I had made.
like image 367
sparcut Avatar asked Jul 08 '16 05:07

sparcut


1 Answers

Your object misses a comma as shown below:

name: "Blue Stilton",
    age: "13"//comma is missing here
    smelly: true

JSON.stringify works fine as shown below.

var cheese_array = [
  {
    name: "Chedder",
    age: "34",
    smelly: true
  },
  {
    name: "Brie",
    age: "4",
    smelly: false
  },
  {
    name: "Blue Stilton",
    age: "13",
    smelly: true
  }
 ];
console.log(JSON.stringify(cheese_array))

However I am not sure how you get a log [object Object], [object Object], [object Object] I am presuming you are console logging something else please check that in your code.

like image 155
Cyril Cherian Avatar answered Oct 21 '22 14:10

Cyril Cherian