I have a nested array of objects as below
JavaScript
x
20
20
1
const person = [
2
{
3
firstName: 'Alex',
4
secondName: 'Lexi',
5
address: [
6
{ place: 'California'},
7
{ pin: 1233 }
8
]
9
},
10
11
{
12
firstName: 'Max',
13
secondName: 'Lui',
14
address: [
15
{ place: 'New York' },
16
{ pin: 3455 }
17
]
18
}
19
]
20
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
JavaScript
1
14
14
1
const renderPerson = () => {
2
person.forEach((item) => {
3
return item.firstName;
4
})
5
}
6
7
const renderAddress = () => {
8
person.forEach((item) => {
9
if(item.firstName === "Max" {
10
return item.address;
11
}
12
}
13
}
14
Then
JavaScript
1
4
1
const html = `<li>${renderPerson()}</li>`;
2
3
document.getElementById("display").innerHTML = html;
4
But it returns undefined. How can solve it?
Advertisement
Answer
You should look up array find()
.
It would look something like this:
JavaScript
1
15
15
1
const person = [
2
{
3
firstName: "Alex",
4
secondName: "Lexi",
5
address: [{ place: "California" }, { pin: 1233 }],
6
},
7
{
8
firstName: "Max",
9
secondName: "Lui",
10
address: [{ place: "New York" }, { pin: 3455 }],
11
},
12
];
13
14
const myPerson = person.find(p => p.firstName === "Max");
15
console.log(myPerson?.address); // [{place: "New York"}, {pin: 3455}]