1
  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 3

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

Sign up to request clarification or add additional context in comments.

Comments

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");
}

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.