Reputation: 2269
I have an array of objects with this structure
mockData: [{
'ONE': [{
id: 11,
...
}, {
id: 4,
...
}]
},
{
'TWO': [{
id: 11,
...
}]
}
]
I want to filter out the item by id (for example with id === 11) and by Object key. For exmaple I want to delete
'ONE': [{
id: 11,
...
}
but leave the
{
'TWO': [{
id: 11,
...
}]
}
I figured out that filter just by id
mockData.map(item => {
return Object.values(item).map(inner => {
return inner.filter(i => i.id !== id)
});
})
This works but it removes the key of the object ('ONE', 'TWO' etc.) and returns data like this
[[{id:3, ...}]],
[[]]
instead of
'TWO': []
All the help with adjusting my function to work properly will be much appreciated.
Also, I'm doing it in Redux reducer, so I can't mutate the initial array.
Upvotes: 0
Views: 61
Reputation: 386654
You need to separate the parts and get the most inner array along with the key and then add this result to the outer array.
const
filter = (array, id) => array.reduce((r, o) => {
var hasContent,
content = Object.assign({}, ...Object.entries(o).map(([k, v]) => {
v = v.filter(o => o.id !== id);
if (v.length) {
hasContent = true;
return { [k]: v };
}
}));
if (hasContent) r.push(content);
return r;
}, []);
var data = { mockData: [{ ONE: [{ id: 11 }, { id: 4 }] }, { TWO: [{ id: 11 }] }] }
console.log(filter(data.mockData, 11));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 728
You can try using the Array.reduce
method.
Example:
const data = [
{
ONE: [{ id: 11 }, { id: 12 }, { id: 13 }],
TWO: [{ id: 11 }, { id: 12 }, { id: 13 }]
}
];
const filtered = data.map(item => {
return Object.keys(item).reduce((prev, key) => {
prev[key] = item[key].filter(({ id }) => id !== 11);
return prev;
}, {});
});
console.log(filtered)
Upvotes: 2