I need to extract listImages
that have a status of ‘Existing` inside of an array. My problem is that it gets its parent array.
Data
lists = [
{
"listID": "1",
"listImages": [
{
"id": "111",
"status": "Existing"
},
{
"id": "222",
"status": "Non-Existing"
}
]
},
{
"listID": "2",
"listImages": [
{
"id": "333",
"status": "Non-Existing"
}
]
}
]
Current Code
const images = lists.map((list) => ({
...list,
listImages: (list.listImages?? []).filter(
({ status }) => status === "Existing"
),
}));
Expected Output
["111"]
>Solution :
Looks like you just want to get the id
. Simply do filter
followed by a map
for each list. If you want to do this process on all lists and merge the arrays to one, use flatMap
.
lists = [
{
"listID": "1",
"listImages": [
{
"id": "111",
"status": "Existing"
},
{
"id": "222",
"status": "Non-Existing"
}
]
},
{
"listID": "2",
"listImages": [
{
"id": "333",
"status": "Non-Existing"
}
]
}
];
const images = lists.flatMap( list => list.listImages.filter(image => image.status === "Existing").map(image => image.id));
console.log(images);