Find a value in array of objects

Viewed 65
  const objectTest = {
    Shoes: [
      { id: 1, name: "xxx", image: "xxxxxx" },
      { id: 2, name: "yyy", image: "yyyyyy" },
    ],
    Top: [
      { id: 1, name: "zzz", image: "zzzzzz" },
      { id: 2, name: "aaa", image: "aaaaaa" },
    ],
  };

I know i can use the find method.

 const item = objectTest.Shoes.find((p) => p.name === "xxx");
 console.log(item);  ///{id: 1, name: 'xxx', image: 'xxxxxx'}

but what if i don't know "xxx" belongs to the Shoes group. How do I find "xxx" and return { id: 1, name: "xxx", image: "xxxxxx" }

3 Answers

Easiest way is to flatten the object values first:

Object.values(objectTest).flat()

then you can find it normally:

const item = Object.values(objectTest).flat().find((p) => p.name === "xxx");

If you want to know which "group" it belonged to, you must iterate over Object.entries(objectTest).

If the schema's of Shoes and Top are the same, you can flatten them like

  const objectTest = {
    Shoes: [
      { id: 1, name: "xxx", image: "xxxxxx" },
      { id: 2, name: "yyy", image: "yyyyyy" },
    ],
    Top: [
      { id: 1, name: "zzz", image: "zzzzzz" },
      { id: 2, name: "aaa", image: "aaaaaa" },
    ],
  };

const findX = (objectTest, name) => {
   return [...objectTest.Shoes, ...objectShoes.Top].find((p) => p.name === "xxx");
}

You can use for-in loop to traverse array, then can find into particular objects array.

const objectTest = {
    Shoes: [
      { id: 1, name: "xxx", image: "xxxxxx" },
      { id: 2, name: "yyy", image: "yyyyyy" },
    ],
    Top: [
      { id: 1, name: "zzz", image: "zzzzzz" },
      { id: 2, name: "aaa", image: "aaaaaa" },
    ],
  };
  
  let obj;
  for(let prop in objectTest) {
    obj = objectTest[prop].find(x=>x.name == "xxx");
    if(obj)
        break;    
  }
  
  console.log(obj)

Related