Just to preface, I have seen multiple questions and answers about using filter
followed by some
, however I cannot seem to get the desired result I am after.
I have an array of objects with the format:
[
{
"accounts": [
{
"products": [
{
"code": "abc123"
}
]
},
...
]
}
]
I am expecting there to be products with differing values of code
. There will only ever be one element in the products
array.
I have a hypothetical whitelist of product codes I would like to filter for of const WHITELIST = ['abc123', 'xyz321']
.
I would like filter the accounts
array such that I am left with an array of the full objects that have code
values that match my whitelist (ie {products: [{code: xxx}]}
).
I did manage to get it working in a slightly long-winded method with:
const filtered = [];
data.forEach(item => {
const {accounts} = item;
accounts.forEach(({products}) =>
products.forEach(({code}) => {
PRODUCT_CODE_WHITE_LIST.includes(code) && filtered.push(item);
})
)
});
return filtered;
However, I’m wondering if this could be streamlined a bit more with filter
, some
or maybe even map
?
As I mentioned at the top, I have seen Q&As on here about replacing the first forEach
with filter
and the rest with some
…
const filtered = data.filter(({accounts}) =>
accounts.some(({products}) =>
products.some(({code}) =>
PRODUCT_CODE_WHITE_LIST.includes(code)
)
)
);
However that doesn’t quite get me the result I’m after and seems to place matched values all within the accounts
section…
How can I achieve this?