0

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?

3
  • You can use filter() to retrieve only the objects within an array matching certain property values. Note that this will return an array though, so you need to either build a string from that array, or return a single specific object from it. Commented Oct 20, 2022 at 14:10
  • @RoryMcCrossan: I am trying to extract address objects if firstName === 'Max' Commented Oct 20, 2022 at 14:13
  • Then you can use find() and extract the data after you found it. Commented Oct 20, 2022 at 14:18

1 Answer 1

2

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}]

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, i guess you're right. find would return the object directly or undefined, making it easier to check if it actually found something. kinda slipped my mind that find is a thing :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.