ES6 - Finding data in nested arrays

前端 未结 1 873
感动是毒
感动是毒 2021-02-01 16:30

In ES6 using find or filter I\'m quite comfortable iterating through to find an element in an array using a value.

However, I\'m trying to get

1条回答
  •  再見小時候
    2021-02-01 17:01

    You have to return something from the callback of the outer find. In fact, for the inner iteration you shouldn't use find but rather some that returns a boolean for whether an element matching the condition exists within the arrray:

    products.find((product) => {
      return product.items.some((item) => {
    //^^^^^^
        return item.name === 'milk';
      });
    });
    

    or in short:

    products.find(product => product.items.some(item => item.name === 'milk'));
    

    Then check whether find found something (not null!) and get its .id, the result should be 03. Alternatively, you can filter for the products containing milk as an item and then map all the results to their id:

    products.filter(product =>
      product.items.some(item => item.name === 'milk');
    ).map(product =>
      product.id
    ) // [03]
    

    0 讨论(0)
提交回复
热议问题