ES6 - Data Search in Nested Arrays

In ES6 using findor filterit is quite convenient for me to iterate over an element in an array using a value.

However, I am trying to get the value from the parent array based on the value from the nested array.

For example, in this data structure:

products: [
  {
    id: 01,
    items: [
      {
        id: 01,
        name: 'apple'
      },
      {
        id: 02,
        name: 'banana'
      },
      {
        id: 03,
        name: 'orange'
      }
    ]
  },
  {
    id: 02,
    items: [
      {
        id: 01,
        name: 'carrot'
      },
      {
        id: 02,
        name: 'lettuce'
      },
      {
        id: 03,
        name: 'peas'
      }
    ]
  },
  {
    id: 03,
    items: [
      {
        id: 01,
        name: 'eggs'
      },
      {
        id: 02,
        name: 'bread'
      },
      {
        id: 03,
        name: 'milk'
      }
    ]
  }
]

If I know of nameeither an idobject milk, is there a way to find out the identifier of the element that it nested?

I currently have this:

products.find((product) => {
  product.find((prod) => {
    return prod.name === 'milk';
  });
});

Which returns an object containing milk.

+4
source share
1 answer

- find. , find, some, , , :

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

:

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

, find - ( null!) .id, 03. filter , , , :

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

Source: https://habr.com/ru/post/1657641/


All Articles