将数据推送到JavaScript对象

时间:2014-08-22 11:30:21

标签: javascript arrays

我有以下JavaScript对象 -

var newArray = { "set1": [], "set2": [] };

我正在尝试推送新数据 -

newArray.set1.push(newSet1);
newArray.set2.push(newSet2);

newSet1newSet2等于 -

[{"test1","test1"},{"test2","test2"}] & [{"test3","test3"},{"test4","test4"}]

然而,当它被推入时,它会创建额外的方括号,最终结果看起来像 -

{ "set1": [[{"test1","test1"},{"test2","test2"}]], "set2": [[{"test3","test3"},{"test4","test4"}]] }

当我真正需要时 -

{ "set1": [{"test1","test1"},{"test2","test2"}], "set2": [{"test3","test3"},{"test4","test4"}] }

我尝试将newArray设置为空白,如 -

var newArray = { "set1": '', "set2": '' };

然而这不起作用。如何调整它以接受集合而不添加额外的括号?

4 个答案:

答案 0 :(得分:2)

使用.concat()

var newArray = { "set1": [], "set2": [] };
newArray.set1 = newArray.set1.concat(newSet1);
newArray.set2 = newArray.set2.concat(newSet2);

答案 1 :(得分:0)

你应该说

newArray.set1.push(newSet1[0]);
newArray.set1.push(newSet1[1]);
newArray.set2.push(newSet2[0]);
newArray.set2.push(newSet2[1]);

答案 2 :(得分:0)

newArray.set1 = newSet1; newArray.set2 = newSet2;

答案 3 :(得分:0)

使用喜欢

var newArray = { "set1": [], "set2": [] };
var arr1 = new Array ("A", "B", "C");
var arr2 = new Array (1, 2, 3);
var multiArr = new Array (arr1, arr2);
    // or
var multiArr = [arr1, arr2];
    // or
var multiArr = [["A", "B", "C"], [1, 2, 3]];

 // you can access the elements of the array by zero-based indices
var firstRow = multiArr[0]; // same as arr1
var secondRowFirstCell = multiArr[1][0]; // 1
newArray.set1.push(multiArr[0]); //so, you need to use this with
newArray.set1.push(multiArr[1]); //so, you need to use this with
console.log(newArray);

DEMO