如何将对象的属性与对象数组的属性相匹配?

时间:2017-05-15 23:12:57

标签: javascript arrays lodash

我有两个对象数组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"}];

1 个答案:

答案 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);