skip to Main Content

Get an element inside an array based on a condition using find is known to me, but what if array is nested with an object?

[{
    _id: 1,
    crew: [{
        name: "A",
        price: "5",
      },
      {
        name: "B",
        price: "10",
      },
    ],
  },
  {
    _id: 2,
    crew: [{
        name: "C",
        price: "15",
      },
      {
        name: "D",
        price: "20",
      },
    ],
  },
];

I want to search by name, let D be an example
Expected result

{
  name: "D",
  price: "20",
},

thank you

3

Answers


  1. You can try using Array.prototype.reduce():

    The reduce() method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

    Code Example:

    const data = [
      {
        _id: 1,
        crew: [
          {
            name: "A",
            price: "5",
          },
          {
            name: "B",
            price: "10",
          },
        ],
      },
      {
        _id: 2,
        crew: [
          {
            name: "C",
            price: "15",
          },
          {
            name: "D",
            price: "20",
          },
        ],
      },
    ];
    
    const searchName = "D";
    
    const crewMember = data.reduce((found, item) => {
      return (
        found || //if match has already been found, return it
        item.crew.find(member => member.name === searchName) // find crew member by name
      );
    }, null);
    console.log(crewMember);
    Login or Signup to reply.
  2. You could try this out

    response.find(el => el.crew?.find(el => el.name === "D")).crew.find(el => el.name === "D")
    
    Login or Signup to reply.
  3. You can do something like this:

    arr.find((obj) => {
       return obj.crew.some((cr) => {
         return cr.name === 'D'
     }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search