6

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); 
davidlebr1
  • 423
  • 2
  • 6
  • 16

2 Answers2

6

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); 
Giovanni P.
  • 1,017
  • 15
  • 23
  • Thank you for your response. But I will have more than one object so it will be "1":.... "2":..... "3": ...... .... ... – davidlebr1 Aug 22 '13 at 14:59
  • then use a while/for loop Dave.in your question it looks like as you just have one object. – cocco Aug 22 '13 at 15:05
  • If your object are stored in an array (or are somehow iterable) you can use a cycle to put the values in the "object" map. – Giovanni P. Aug 22 '13 at 15:09
  • I'm trying something with a loop like : var data = {}; var objVal = {}; for(var i in data) { var object = {}; object[i] = $.extend({}, objVal, data);} JSON.stringify(object); // but it doesn't work :( – davidlebr1 Aug 22 '13 at 15:16
  • While a while loop is certainly possible, see my answer for an underscore based solution – Dexygen Aug 22 '13 at 15:42
5

I found the solution !

I do an for loop on the object. And I iterate on each element in the object. Thank you for your help. The answer of @Giovanni help me to found the solution.

Solution:

var data = {}; //values....
var objVal = {}; //other values....
var final = {};
var index = 1;
for(var key in data)
{
    final[index] = data[key];
    index = index + 1;
}
final[index] = objVal;
JSON.stringify(final);

And the output is :

{"1":{"valeur":"dfgdfg","usager":"experttasp","date":"2013-08-23 10:36:54"},"2":{"valeur":"uuuuuuuuuu","commentaire":"defg","usager":"experttasp","date":"2013-08-23 10:37:26"},"3":{"valeur":"uuuuuuuuuu","commentaire":"yesssss","usager":"experttasp","date":"2013-08-23 10:38:38"}}
davidlebr1
  • 423
  • 2
  • 6
  • 16