Stringify JavaScript object

davidlebr1 picture davidlebr1 · Aug 22, 2013 · Viewed 32.8k times · Source

I'm looking to stringify an object.

I want in output like this

{"1":{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, "2": {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}}

But I get this

{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}

What I do

var objVal = {}; //value....
var data = {}; //other value....
var object = $.extend({}, objVal, data); //concat the object 
JSON.stringify(object); 

Answer

Giovanni P. picture Giovanni P. · Aug 22, 2013

When you concat the object, you get an array; you want a map with two elements, using the id "1" and "2"

var objVal = {};   //value....
var data = {};     //other value....

var object = {}
object["1"] = objVal;
object["2"] = date;
JSON.stringify(object);