Skip to content
Advertisement

Looping through an array of objects and filter using a key

I have a nested array of objects as below

const person = [
   {
     firstName: 'Alex',
     secondName: 'Lexi',
     address: [
       { place: 'California'},
       { pin: 1233 }
     ]
  },

{
     firstName: 'Max',
     secondName: 'Lui',
     address: [
       { place: 'New York' },
       { pin: 3455 }
     ]
  }   
]

I would like to loop through the array and get the address object corresponding to the firstName ‘Max’.

I can use this data to generate links and their sublinks (on clicking the links)

I have attempted the following

const renderPerson = () => {
  person.forEach((item) => {
    return item.firstName;
  })
}

const renderAddress = () => {
   person.forEach((item) => {
     if(item.firstName === "Max" {
        return item.address;
  }
}
}

Then

const html = `<li>${renderPerson()}</li>`;

document.getElementById("display").innerHTML = html;

But it returns undefined. How can solve it?

Advertisement

Answer

You should look up array find().

It would look something like this:

const person = [
  {
    firstName: "Alex",
    secondName: "Lexi",
    address: [{ place: "California" }, { pin: 1233 }],
  },
  {
    firstName: "Max",
    secondName: "Lui",
    address: [{ place: "New York" }, { pin: 3455 }],
  },
];

const myPerson = person.find(p => p.firstName === "Max");
console.log(myPerson?.address); // [{place: "New York"}, {pin: 3455}]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement