我有一个愚蠢的问题,可能是由于我的语法。如何将对象arr[j]
中的所有键动态推送到对象arr[i]
?
var arr = [{key:["data1","data2"]},{key:"data"}];
var i = 0;
var j = 1;
for(var key in arr[i]){
arr[i][key].push(arr[j][key]);
// arr[i][key] is an array, arr[j[key;] is a string
}
而不是粗暴地输入所有内容(这对我有用):
arr[i][key1].push(arr[j].key1);
arr[i][key2].push(arr[j].key2);
然后 Arr[i]
将以数组的形式包含其先前的信息和对象2信息。基本上,我是连接JavaScript对象。最后,arr[i]
应如下所示:
key1:[arr[i].key1Value,arr[j].key1Value]
key2:[arr[i].key2Value,arr[j].key2Value]
提前致谢!!
答案 0 :(得分:1)
相对简单:
var arr = [{key:["data1","data2"]},{key:"data"}],
i = 0,
j = 1,
target = arr[i],
source = arr[j];
target.key.push(source.key);
如果源有多个键,请尝试改为:
var arr = [{key:["data1","data2"]},{key:"data", key1: "data1", key2: "data2"}],
i = 0,
j = 1,
target = arr[i],
source = arr[j];
for(var key in source){ // Loop over the keys in the source
target.key.push(source[key]); // And add them to the target's `key` array.
}
结果:
[
{ key: ["data1", "data2", "data", "data1", "data2"]},
{ key: "data", key1: "data1", key2: "data2"}
]
答案 1 :(得分:0)
如果我理解你想要达到的目标,我并不是百分百肯定,但这可能会有所帮助:
var arr = [{key:["data1","data2"]},{key:"data"}];
var target = [];
arr.forEach( function(value,index){
target['key' + index] = value;
});
输出:
target.key0 : { key: [ 'data1' 'data2' ]}
target.key1 : { key: [ 'data' ]}