小能豆

Filter array of objects using the objects array property

javascript

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


阅读 73

收藏
2023-12-02

共1个答案

小能豆

To achieve the desired result, you need to filter the main array based on the condition for the id and then modify the events array for the selected object. Here’s one way to do it:

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' }],
  },
];

const idToRemove = 1;
const eventNameToRemove = 'event 1';

const updatedData = data.map((item) => {
  if (item.id === idToRemove) {
    // Filter the events array for the selected object
    const updatedEvents = item.events.filter((event) => event.name !== eventNameToRemove);
    // Return a new object with the updated events array
    return { ...item, events: updatedEvents };
  }
  return item;
});

console.log(updatedData);

This code uses the map function to iterate over the main array. For the selected object (where id === idToRemove), it filters the events array based on the condition event.name !== eventNameToRemove. The resulting array (updatedData) contains the modified objects.

2023-12-02