2017-05-15 164 views
0

我有两个对象的数组,hListsList。我试图给sList中的每个对象一个匹配hList.ID的属性(如果存在并且尚未设置)。我有点纠结于逻辑,但有人可以帮我吗?如何将对象的属性与对象数组的属性进行匹配?

var sList=[{name:"s1",id:"a"},{name: "s2",id:"b"},{name: "s3",id:"c"},{name: "s4",id:"d"}]; 
    var hList=[{name: "h1",id:"x"},{name: "h2",id:"y"},{name: "h3",id:"z"}]; 

到目前为止我有:

try{  
    for(i in sList) 
    { 
    var s=sList[i]; 
    //find hList object that matches sList.id value 
    var h=_.filter(hList.id,function(i){return(i==s.hID)}); 
    //if no hList.id match the sList.hID 

    //find hList object that doesnt match any 

    //set the source id to the hList object id 

    } 

}catch(err){console.log("err: ",err);} 

目标:(只有一个hList.id可以匹配sList.hID如果hList.id犯规存在sList.hID应该是不确定的。)

var sList=[{name:"s1",id:"a",hID:"x"},{name: "s2",id:"b",hID="y"},{name: "s3",id:"c",hID="z"},{name: "s4",id:"d",hID=undefined}]; //goal: set sList.hID to match an hList.id 
var hList=[{name: "h1",id:"x"},{name: "h2",id:"y"},{name: "h3",id:"z"}]; 

回答

0

var sList=[{name:"s1",id:"a"},{name: "s2",id:"b"},{name: "s3",id:"c"},{name: "s4",id:"d"}]; 
 
var hList=[{name: "h1",id:"x"},{name: "h2",id:"y"},{name: "h3",id:"z"}]; 
 
    
 
    
 
sList = sList.map((item, index) => { 
 
    item.hId = hList[index] ? hList[index].id : undefined; 
 
    return item 
 
}) 
 

 
console.log(sList);

+0

这很好,我将不得不阅读'map'函数。谢谢! – Rilcon42

相关问题