How to find data in nested arrays with JavaScript?

To find data in nested arrays with JavaScript, we use the find and some methods.

For instance, we write

const 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",
      },
    ],
  },
];
const product = products.find((product) =>
  product.items.some((item) => item.name === "milk")
);

to call products.find with a callback that checks if any object in the items array property has the name property equal to 'milk' with some.

some returns true if any item matches the condition we return in the callback.

find returns the first item where some returns true.