问题描述
我必须使用两个包含两个到三个属性的对象的数组来创建一个自定义对象。 现在,基于匹配项的数量,我创建了对象。 在这里,我不想使用太多变量。 不使用中间变量,我想编写代码
码
var fn = function() {
var list1 = [{aId: 0, name: 'item1'},
{aId: 1, name: 'item2'},
{aId: 2, name: 'item3'}],
list2 = [ { id: 0, label: 'one', actions: [ 0, 1, 2 ] },
{ id: 1, label: 'two', actions: [ 0, 2 ] } ],
customObj ={};
for(var i=0; i<list1.length; i++) {
for(var j=0; j<list2.length; j++){
customObj[list2[j].id] = {};
for(var k=0; k<list2[j].actions.length; k++){
if(list1[i].aId == list2[j].actions[k]){
customObj[list2[j].id][list1[i].name] = true
}
}
}
}
return customObj;
}
要求的输出:
customObj = {
0: {
item1: true,
item2: true,
item3: true
},
1: {
item1:true,
item3:true
}
}
谁能建议我在哪里做错了?
1楼
您正在为整个对象分配一个值,而不只是一个属性。
在您的条件内,您只需要customObj[list2[j].id][list1[i].name] = true 。
在此处使用方括号访问属性(与点相反,如customObj.0.item1点),可以 。
因此,您的最终代码如下所示:
var fn = function() {
var list1 = [{aId: 0, name: 'item1'},
{aId: 1, name: 'item2'},
{aId: 2, name: 'item3'}],
list2 = [ { id: 0, label: 'one', actions: [ 0, 1, 2 ] },
{ id: 1, label: 'two', actions: [ 0, 2 ] } ],
customObj ={};
for(var i=0; i<list1.length; i++) {
for(var j=0; j<list2.length; j++){
for(var k=0; k<list2.actions.length; k++){
if(list1[i].aId == list2[j].actions[k]){
customObj[list2[j].id][list1[i].name] = true;
}
}
}
}
return customObj;
}
2楼
它正在使用这段代码,并且循环也减少了。
var fn = function() {
var list1 = [{aId: 0, name: 'item1'},
{aId: 1, name: 'item2'},
{aId: 2, name: 'item3'}],
list2 = [{ id: 0, label: 'one', actions: [ 0, 1, 2 ] },
{ id: 1, label: 'two', actions: [ 0, 2 ] } ],
customObj ={};
for(var i=0; i<list2.length; i++) {
customObj[list2[i].id] = {};
for(var j=0; j<list1.length; j++) {
if(list2[i].actions.indexOf(list1[j].aId) > -1)
customObj[list2[i].id][list1[j].name] = true
}
}
return customObj;
}