我正在尝试运行for循环来创建新的javascript对象并添加到现有的javascript对象而不替换。
例如,我试图将此作为输出创建,而不是每次都覆盖组[i](只添加数字[i]数据):
{
"group1": {
"number1": "data",
"number2": "data",
"number3": "data"
},
"group2": {
"number1": "data",
"number2": "data"
}
}
我的循环看起来像这样:
var array = [{
"groupName": "group1",
"number": "number1",
"data": "data"
}, {
"groupName": "group1",
"number": "number2",
"data": "data"
}, {
"groupName": "group1",
"number": "number3",
"data": "data"
}, {
"groupName": "group2",
"number": "number1",
"data": "data"
}, {
"groupName": "group2",
"number": "number2",
"data": "data"
}]
var groupLinks = {};
for(i = 0; i < array.length; i++) {
groupLinks[array[i].groupName] = {
[array[i].number]: array[i].data
}
正如您在此代码中所看到的,我的循环每次只会替换“group1”和“group2”。
答案 0 :(得分:5)
这就是我接近这个的方法:
var array = [{
"groupName": "group1",
"number": "number1",
"data": "data"
}, {
"groupName": "group1",
"number": "number2",
"data": "data"
}, {
"groupName": "group1",
"number": "number3",
"data": "data"
}, {
"groupName": "group2",
"number": "number1",
"data": "data"
}, {
"groupName": "group2",
"number": "number2",
"data": "data"
}];
var groupLinks = {};
array.forEach(
function (element)
{
var groupName = element.groupName;
(groupLinks[groupName] = groupLinks[groupName] || {})
[element.number] = element.data;
}
);
console.log(groupLinks);
&#13;
这里我使用||
运算符创建一个新组,当没有时,在每次迭代时覆盖现有的groupLinks[groupName]
,并使用forEach
构造循环数组元素
答案 1 :(得分:0)
试试这个:
var array = [{
"groupName": "group1",
"number": "number1",
"data": "data"
}, {
"groupName": "group1",
"number": "number2",
"data": "data"
}, {
"groupName": "group1",
"number": "number3",
"data": "data"
}, {
"groupName": "group2",
"number": "number1",
"data": "data"
}, {
"groupName": "group2",
"number": "number2",
"data": "data"
}]
var groupLinks = {};
array.forEach(function(el){
if(groupLinks[el.groupName]){
groupLinks[el.groupName][el.number] = el.data
}
else{
groupLinks[el.groupName] = {};
groupLinks[el.groupName][el.number] = el.data
}
});
console.log(groupLinks);
答案 2 :(得分:0)
如果您不害怕ES2015,那么减少工作应该适合您
let array = [{"groupName":"group1","number":"number1","data":"data"},{"groupName":"group1","number":"number2","data":"data"},{"groupName":"group1","number":"number3","data":"data"},{"groupName":"group2","number":"number1","data":"data"},{"groupName":"group2","number":"number2","data":"data"}];
let groupLinks = array.reduce((gl, group) => {
gl[group.groupName] = Object.assign({
[group.number]: group.data
}, gl[group.groupName]);
return gl;
}, Object.create(null));
console.log(groupLinks);
&#13;
答案 3 :(得分:0)
请试试这个:
var groupLinks = {};
for(i = 0; i < array.length; i++) {
var groupLinks2 = groupLinks[array[i].groupName];
if(!groupLinks2){
groupLinks2 ={};
var a = array[i].number;
groupLinks2[a] = array[i].data;
}else{
var a = array[i].number;
groupLinks2[a] = array[i].data;
}
groupLinks[array[i].groupName] = groupLinks2;
}