简体   繁体   English

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

[英]How to match a property of an object to a property of an array of objects?

I have two arrays of objects, hList and sList . 我有两个对象数组, hListsList I am trying to give each object in sList a property that matches an hList.ID , if one exists and is not already set. 我试图给sList的每个对象一个与hList.ID匹配的hList.ID (如果存在且尚未设置)。 Im kind of tangled in the logic though, can someone help me out? 我在逻辑上有点纠结,有人可以帮我吗?

  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"}];

so far I have: 到目前为止,我有:

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);}

GOAL: (only one hList.id can match an sList.hID . If an hList.id doesnt exist the sList.hID should be undefined.) 目标:(只有一个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"}];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有对象数组属性的Mongodb文档:该数组的属性如何匹配? - Mongodb document with array of objects property: how match property of this array? 匹配具有 object 属性的数组 - Match an array with an object property 比较2个对象数组。 按 id 匹配,将对象属性推入数组 - compare 2 array of objects. match by ids, push object property into array 如何根据每个 object 中的字符串属性数组深入比较/匹配数组中的对象? - How to deep compare/match objects in an array, based on an array of strings property in each object? 根据匹配在对象数组内设置对象的属性:React JS - Setting a property of an object inside array of objects based on a match: React JS 如果属性与比较值不匹配,如何更改数组中 object 属性的值? - How to change value for object property in array if property not match with compared value? 如何根据对象的属性对对象数组进行排序 - How to sort array of objects according to a property of the object 如何访问对象数组中的对象属性 - How to access object property in an array of objects 如何在对象数组中添加附加的 object 属性? - How to add aditional object property in array of objects? 如何在对象数组中查找和编辑对象的属性? - How to find and edit property of object in the array of an objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM