6

我正在寻找字符串化一个对象。

我想要这样的输出

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

但我明白了

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

我所做的

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

2 回答 2

6

当你连接对象时,你会得到一个数组;你想要一个包含两个元素的地图,使用 id "1" 和 "2"

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

var object = {}
object["1"] = objVal;
object["2"] = date;
JSON.stringify(object); 
于 2013-08-22T14:52:53.990 回答
5

我找到了解决方案!

我在对象上做了一个 for 循环。我迭代对象中的每个元素。谢谢您的帮助。@Giovanni 的回答帮助我找到了解决方案。

解决方案:

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

输出是:

{"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"}}
于 2013-08-23T14:50:27.837 回答