将多个单独的对象转换为1个对象数组

时间:2015-03-04 19:58:46

标签: javascript underscore.js

我有两个Hash对象。

一:

{"name" : "one" , "color" : "red" } 

二:

{"name" : "two" , "color" : "blue" } 

我正在尝试将这两个对象转换为看起来像这样的东西:

[{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" } ]

如何使用javascript实现此目的?

我也在使用下划线。

另外 - 当我有新对象时,我会收到更多我希望推送的单个对象 -

Three :   {"name" : "three" , "color" : "red" } 

结果是 -

 Result :        [{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" }, {"name" : "three" , "color" : "red" } ]

谢谢!

3 个答案:

答案 0 :(得分:3)



var a = {"name" : "one" , "color" : "red" }; 
var b = {"name" : "two" , "color" : "blue" };
var res = [a, b];
console.log(res);




或使用push这样

var res = [];
res.push(a);
res.push(b);

答案 1 :(得分:2)

试试这个:

var one = {"name" : "one" , "color" : "red" }; 
var two = {"name" : "two" , "color" : "blue" };
var array = [one, two];

或者像这样使用推送:

var array = [];
array.push(one);
//array is now equal to [one]
array.push(two);
//array is now equal to [one,two]

或者像这样使用unshift:

var array = [];
array.unshift(one);
// array is now equal to [one]
array.unshift(two);
// array is now equal to [two, one]  

基本上,您只需要创建变量来捕获Hash对象值,并使用您创建的变量来创建数组。

您可以执行其他值:

var three = {"name" : "three", "color" : "red" };
var array.push(three);

显示所有值:

for (var i = 0; i < array.length; i++) {
    console.log(array[i]);
}

答案 2 :(得分:1)

如果你有不明数量的对象,你可以使用数组的push函数:

var res = [];
var one = {"name" : "one" , "color" : "red" }; 
var two = {"name" : "two" , "color" : "blue" };
res.push(one);
res.push(two);
// res is now: [{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" }]
res.push({"name" : "three"});
// res is now: [{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" }, {"name" : "three"}]