Home > front end >  How do I search the object inside the array inside the array?
How do I search the object inside the array inside the array?

Time:12-10

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",
    },
  ],
];

CodePudding user response:

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)

CodePudding user response:

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

  • Related