Reputation: 53
How do I access the following keys within this array of objects using the 'map' method? I want to access:
I get undefined for the following fields when I use
a.map((d) => console.log(d.moreInfo.id));
. I want to use the 'map' method itself so that I can render this content in my React application.
let a = [
{
"Id": "huih23432",
"name": "Kevin",
"dob": "26/06/1995",
"nid": "34535353543",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
}
},
{
"moreInfo": [
{
"id": "243423423423",
"dob": "16/07/1990",
"name": "JD",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
},
"distances": {
"fore": "0.91",
"towards": "0.5"
}
}
]
}
];
Upvotes: 0
Views: 46
Reputation: 11001
Actually you data array of objects and each object has different props. You can use destructuring with default values.
let a = [
{
Id: "huih23432",
name: "Kevin",
dob: "26/06/1995",
nid: "34535353543",
images: {
id: "https://picsum.photos/200",
nid: "https://picsum.photos/200",
},
},
{
moreInfo: [
{
id: "243423423423",
dob: "16/07/1990",
name: "JD",
images: {
id: "https://picsum.photos/200",
nid: "https://picsum.photos/200",
},
distances: {
fore: "0.91",
towards: "0.5",
},
},
],
},
];
a.map(({ moreInfo: [{ id, distances: { fore } = {} }] = [{}] }) =>
console.log({ id, fore })
);
Upvotes: 0
Reputation: 2864
Try this.
let a = [
{
"Id": "huih23432",
"name": "Kevin",
"dob": "26/06/1995",
"nid": "34535353543",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
}
},
{
"moreInfo": [
{
"id": "243423423423",
"dob": "16/07/1990",
"name": "JD",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
},
"distances": {
"fore": "0.91",
"towards": "0.5"
}
}
]
}
];
a.filter(d => d.moreInfo)
.map((d)=>{
const moreInfoObj = d.moreInfo.find(y => y.id);
console.log("'id' inside 'moreInfo': " + moreInfoObj.id);
console.log("'fore' inside 'distances': " + moreInfoObj.distances.fore);
});
Upvotes: 1