简体   繁体   中英

How do I search the object inside the array inside the array?

There are 2 arrays in the array. There are objects in them. How can I find the one whose name is "Sneijder"?

const players = [
  [
    {
      id: 1,
      name: "Hagi",
    },
    {
      id: 2,
      name: "Carlos",
    },
  ],
  [
    {
      id: 3,
      name: "Zidane",
    },
    {
      id: 4,
      name: "Sneijder",
    },
  ],
];

You could flatten the array with flat then find your item in the resulting flattened array:

 const players = [ [ { id: 1, name: "Hagi", }, { id: 2, name: "Carlos", }, ], [ { id: 3, name: "Zidane", }, { id: 4, name: "Sneijder", }, ], ]; const player = players.flat().find((p) => p.name === "Sneijder") console.log(player)

You can use either of the 3 combinations or any different than these. All will give the same result but the complexity can be different for other examples having required object in the beginning or middle.

 const players = [ [{ id: 1, name: "Hagi", }, { id: 2, name: "Carlos", }, ], [{ id: 3, name: "Zidane", }, { id: 4, name: "Sneijder", }, ], ]; let player = ""; players.forEach(x => player = x.find(y => y.name === "Sneijder")); console.log("Method 1", player); player = players.flat().find(y => y.name === "Sneijder"); console.log("Method 2", player); players.some(x => { const [x1, x2] = x; if (x1.name === "Sneijder") return player = x1; if (x2.name === "Sneijder") return player = x2; }); console.log("Method 3", player);

you can use Array.prototype.concat to merge arrays and then find by name

const sneijderObj = [].concat.apply([], players).find(x => x.name === 'Sneijder');
console.log(sneijderObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM