使用现有键将对象合并到数组中

时间:2013-02-09 19:23:12

标签: javascript

我多次创建以下对象:

id : {
    "hp" : hp,
    "row" : startY,
    "square" : startX
}

我希望使用id作为键来创建这些对象的数组,以获得一个如下所示的对象:

1 : {
    "hp" : 1,
    "row" : 2,
    "square" : 3
},
2 : {
    "hp" : 4,
    "row" : 5,
    "square" : 6
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是一个示例,它将为您提供所需的对象数组:

<强> SEE WORKING JSFIDDLE DEMO HERE

以下代码:

var model = { id : {
    "hp" : "",
    "row" : "",
    "square" : ""
} }

function keystempl(args)
{
   var args = Array.prototype.slice.call(args,0);
    var templ = args[0];
    var newo ={};

    var keys = [];
    for(var k in templ) 
    {
        keys.push(k);
    }

    for(var i=0;i<keys.length;i++)
    {
        newo[keys[i]] = args[i + 1]; 
    }
    return newo; 

}

var arr = [];
var obj = keystempl([model["id"],"myhp","myrow","mysquare"]);
var obj2 = keystempl([model["id"],"myhp2","myrow2","mysquare2"]);

arr.push(obj);
arr.push(obj2);

示例用法如下:

var myarray = [];

myarray.push(keystempl([model["id"],"myhp","myrow","mysquare"]));
myarray.push(keystempl([model["id"],"myhp2","myrow2","mysquare2"]));
//YOUR ARRAY "myarray" NOW HAS TWO OBJECTS IN IT WITH THOSE VALUES