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

时间:2019-08-30 14:30:40

标签: javascript arrays

我在该站点上进行了搜索,并阅读了几篇有关reduce,map和filter的文章,但我想我只是不知道要搜索什么。我正在API上运行几个查询,首先在XYZ中运行搜索#1,然后使用搜索#1的结果,运行搜索#2,并使用搜索#1获得的结果数组中的一个属性。基本上,它遵循了承诺的链条,并从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 ....


 }    
}

1 个答案:

答案 0 :(得分:1)

使用.find代替.filter:

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