Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading