I am using a map to ‘filter’ my data, but I’m getting the empty array pieces in the result. How does one alter the code to achieve this?
const WHITE_LIST = ['123', '321'];
const mapped = items.map((item) => ({
...item, accounts: item.accounts.map((acc) => ({
...acc, products: acc.products.filter((prod) => WHITE_LIST.includes(prod.code))
}))
}));
console.log(mapped)
<script>
const items = [
{
"accounts": [
{
"products": [
{
"code": "123",
}
]
},
{
"products": [
{
"code": "321",
}
]
},
{
"products": [
{
"code": "765",
}
]
},
{
"products": [
{
"code": "345",
}
]
},
]
}
];
</script>
Current result:
[
{ products: [ [Object] ] },
{ products: [ [Object] ] },
{ products: [] },
{ products: [] }
]
Expected result:
[
{ products: [ [Object] ] },
{ products: [ [Object] ] }
]
2
Answers
After some hints and tips, I have gotten it to work by adding an extra filter within the existing loops, to filter after the accounts map
Just add a filter to end