0

我多次创建以下对象:

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

我想将这些对象id作为键创建一个数组,以获得一个看起来像这样的对象:

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

我该怎么做?

4

1 回答 1

0

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

在此处查看有效的 JSFIDDLE 演示

下面的代码:

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
于 2013-02-09T19:48:24.477 回答