简洁地从对象数组中获取一个对象属性,其中另一个属性与搜索匹配



我在这个网站上搜索并阅读了几篇关于reduce,map和filter的文章,但我想我只是不知道要搜索什么。我正在 API 上运行多个查询,首先我运行搜索 #1 的 XYZ,然后使用搜索 #1 的结果,我使用搜索 #1 获得的结果数组中的一个属性运行搜索 #2。基本上,它沿着承诺链向下,从API获取更多详细信息。我可以通过作弊/解决方法使其工作,但感觉必须有一种更简洁的 ES6 方法来做到这一点。

async function LoopOverArrayAndRunSearch(json) {
for await (let item of json) {
searchNumber1(item.property1).then(data => {
// Find the items where the search name matches the result name
let nameMatchExactlyArray = data.filter(apiItem => apiItem.name === item.property1);
// get the id from the first value of the array
console.log(nameMatchExactlyArray[0].id);    // this feels sloppy!
let matchingID = nameMatchExactlyArray[0].id;
// run search2 using the matchingID
searchNumber2(matchingID).then ....

}    
}

使用 .find 而不是 .filter:

let foundId = (data.find(apiItem => apiItem.name === item.property1)).id;

最新更新