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"]
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);
Here you have both imperative and declarative solutions. You can change named functions to arrow functions and make it even a single line but I don't think that we have to follow that ugly coding style where no one (not even future you) understands the code.
lists = [
{
"listID": "1",
"listImages": [
{
"id": "111",
"status": "Existing"
},
{
"id": "222",
"status": "Non-Existing"
}
]
},
{
"listID": "2",
"listImages": [
{
"id": "333",
"status": "Non-Existing"
}
]
}
]
// Imperative solution
const images = [];
lists.forEach(list => {
list.listImages.forEach(image => {
if(image.status === 'Existing'){
images.push(image.id);
}
})
});
console.log(images);
// Declarative solution
const data = lists.flatMap(function getAllImages(list){
return list.listImages;
}).filter(function getExistingImages(image) {
return image.status === 'Existing';
}).map(function getIds(image){
return image.id
});
console.log(data);