3
  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" }

C Z
  • 57
  • 6

3 Answers3

3

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).

pilchard
  • 12,414
  • 5
  • 11
  • 23
Adassko
  • 5,201
  • 20
  • 37
1

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");
}
g.p
  • 312
  • 1
  • 5
1

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)
harpal
  • 426
  • 4
  • 12