gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:27:34 26 4
gpt4 key购买 nike

给定以下对象数组:

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

如果整数数组与 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);

关于javascript - 将整数数组与对象数组进行比较并返回属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com