[英]Merging objects into array with existing keys
I am creating the following object multiple times: 我多次创建以下对象:
id : {
"hp" : hp,
"row" : startY,
"square" : startX
}
and I want to make an array of those object using id
as the key, to have an object that will look like this: 并且我想使用id
作为键对那些对象进行数组处理,以使对象看起来像这样:
1 : {
"hp" : 1,
"row" : 2,
"square" : 3
},
2 : {
"hp" : 4,
"row" : 5,
"square" : 6
}
How can I do it? 我该怎么做?
Here's an example that will give you the array of objects like you want: 这是一个示例,它将为您提供所需的对象数组:
SEE WORKING JSFIDDLE DEMO HERE 在这里查看工作的JSFIDDLE DEMO
Code below: 代码如下:
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);
An example usage would be like this: 用法示例如下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.