我有两个对象数组hList
和sList
。我试图给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 :(得分: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);