Stringify JavaScript object

ぃ、小莉子 提交于 2019-12-06 00:14:01

问题


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); 

回答1:


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); 



回答2:


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"}}


来源:https://stackoverflow.com/questions/18383854/stringify-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!