I have an array that I'm trying to filter:
const elements = ['apple'];
const objects = [
{ id: 1, fruit:[{"name": "apple" },{"name": "banana" }]},
{ id: 2, fruit:[{"name": "apple" },{"name": "orange" }]},
{ id: 3, fruit:[{"name": "orange" },{"name": "banana" }]},
{ id: 4, fruit:[{"name": "orange" },{"name": "banana" }]}
];
const results = objects.filter(obj => obj.fruit.filter( ele => elements.includes(ele.name)));
console.log(results);
I am getting the output as below but this not what I am expecting:
{id: 1, fruit:[{"name": "apple" },{"name": "banana" }]
{id: 2, fruit:[{"name": "apple" },{"name": "banana" }]
I want the output as below:
{ id: 1, fruit:[{"name": "apple" }]}
{ id: 2, fruit:[{"name": "apple" }]}
You could filter fruit and if it has elements take the outer object as result.
const
elements = ['apple'],
objects = [{ id: 1, fruit: [{ name: "apple" }, { name: "banana" }] }, { id: 2, fruit: [{ name: "apple" }, { name: "orange" }] }, { id: 3, fruit: [{ name: "orange" }, { name: "banana" }] }, { id: 4, fruit: [{ name: "orange" }, { name: "banana" }] }],
results = objects.reduce((r, o) => {
const fruit = o.fruit.filter(({ name }) => elements.includes(name));
if (fruit.length) r.push({ ...o, fruit });
return r;
}, []);
console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With