繁体   English   中英

将整数数组与对象数组进行比较并返回属性

[英]Compare array of ints with Array of Objects and return property

给定以下对象数组:

var arrayOfObjs = [{
    id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
    typeID: 2
  },
  {
    id: "270d8355-d8b6-49c4-48ac-97a44422c705",
    typeID: 3
  },
  {
    id: "sdks7878-d8b6-49c4-48ac-97a44422c705",
    typeID: 4
  }
];

和一个整数数组:

var arrayOfInts = [2, 4];

如果 int 数组与 arrayOfObjects 匹配,我将如何比较两者并返回一个 ID 数组。

回报应该是:

var matchingIDs = [
    "d8eed6df-9f12-47d4-5b71-3352a92ebcf0", 
    "sdks7878-d8b6-49c4-48ac-97a44422c705"
];


var missingIDs = ["270d8355-d8b6-49c4-48ac-97a44422c705"];

使用array.prototype.filterarray.prototype.includesarray.prototype.map

 var datas = [{ id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0", typeID: 2 }, { id : "270d8355-d8b6-49c4-48ac-97a44422c705", typeID: 3 }, { id : "sdks7878-d8b6-49c4-48ac-97a44422c705", typeID: 4 }]; var arrayOfInts = [2, 4]; var matchingIDs = datas.filter(d => arrayOfInts.includes(d.typeID)).map(e => e.id); var missingIDs= datas.filter(d => !arrayOfInts.includes(d.typeID)).map(e => e.id); console.log('matchingIDs: ', matchingIDs); console.log('missingIDs: ', missingIDs);

实现这一点的方法很多,我选择了 map\\filter 用法,因为 javascript 是一种函数式语言。

 const allItems = [{ id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0", typeID: 2 }, { id : "270d8355-d8b6-49c4-48ac-97a44422c705", typeID: 3 }, { id : "sdks7878-d8b6-49c4-48ac-97a44422c705", typeID: 4 }]; const validIds = [2, 4]; const filteredItems = allItems .filter(({typeID})=> validIds.includes(typeID)) .map(({id})=>id) console.log(filteredItems)

使用 lodash,您可以使用带有_.keyBy()_.at()_.map()的链来实现这一点:

 var arrayOfObjs = [{"id":"d8eed6df-9f12-47d4-5b71-3352a92ebcf0","typeID":2},{"id":"270d8355-d8b6-49c4-48ac-97a44422c705","typeID":3},{"id":"sdks7878-d8b6-49c4-48ac-97a44422c705","typeID":4}]; var arrayOfInts = [2, 4]; var result = _(arrayOfObjs) .keyBy('typeID') // get a dictionary of objects by their type ids .at(arrayOfInts) // get the objects that matches the array of ints .map('id') // map each object to the id .value(); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM