Im trying to get my head round this not sure if its even possible this way but just cant seem to get the hang of it.
I have and array of object and each oject has a few values and another array of ojects. Basically i need to filter the main array and remove a singleobject from the events array.
Here is the data array
let data = [
{
id: 1,
date: '2023-10-01',
events: [{ id: '1a', name: 'event 1' }, { id: '1b', name: 'event 2' }],
},
{
id: 2,
date: '2023-10-02',
events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],
},
{
id: 3,
date: '2023-10-03',
events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],
},
];
Example of what i want to do is filter the data if the id == 1 then if event.name == `event 1` ->
let data = [
{
id: 1,
date: '2023-10-01',
events: [{ id: '1a', name: 'event 1'}],
},
{
id: 2,
date: '2023-10-02',
events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],
},
{
id: 3,
date: '2023-10-03',
events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],
},
];
Here is what i have tried to do but i just cant get the hang of it
console.log(data.filter((item) => item.id !== '1')[0].events.filter((event) => event.id != '1b'))
I Have also tried to filter then filter that but cant i seem to get it either
const filterd = (data.filter((item) => item.id == '1'))
console.log(filterd.filter((event) => event.id == '1a'))
Any help or suggestions welcome Thanks
3
Answers
You’re not looking to filter
data
itself. You’re looking to loop overdata
and, if a given condition is met on an object in that loop, filter a property on that object.For example:
If you want to create a new array, not mutating any existing array, then:
Let’s say that your second array looks something like this:
Where
id
is theid
to find in the first array, andevent_name
is the value to filter theevents
property in the first array by;Then you could use a
for-in
loop as follows: