1

Given is following data structure

const list = [
  {
    title: 'Section One',
    data: [
      {
        title: 'Ay',
      },
      {
        title: 'Bx',
      },
      {
        title: 'By',
      },
      {
        title: 'Cx',
      },
    ],
  },
  {
    title: 'Section Two',
    data: [
      {
        title: 'Ay',
      },
      {
        title: 'Bx',
      },
      {
        title: 'By',
      },
      {
        title: 'Cx',
      },
    ],
  },
];

What i want to do ist to filter this list based on title property in the data array of each object. An example would be to have the list where the title property of the childs starts with "B", so the list will look like that:

const filteredList = [
  {
    title: 'Section One',
    data: [
      {
        title: 'Bx',
      },
      {
        title: 'By',
      }
    ],
  },
  {
    title: 'Section Two',
    data: [
      {
        title: 'Bx',
      },
      {
        title: 'By',
      }
    ],
  },
];

What i tried so far was something like that:

 const items = list.filter(item =>
      item.data.find(x => x.title.startsWith('A')),
    );

or

const filtered = list.filter(childList => {
  childList.data.filter(item => {
    if (item.title.startsWith('B')) {
      return item;
    }
    return childList;
  });
});

But i think i am missing a major point here, maybe some of you could give me a tip or hint what i am doing wrong

Best regards

1 Answer 1

1

Your issue is that you're doing .filter() on list. This will either keep or remove your objects in list. However, in your case, you want to keep all objects in list and instead map them to a new object. To do this you can use .map(). This way you can map your objects in your list array to new objects which contain filtered data arrays. Here's an example of how you might do it:

const list=[{title:"Section One",data:[{title:"Ay"},{title:"Bx"},{title:"By"},{title:"Cx"}]},{title:"Section Two",data:[{title:"Ay"},{title:"Bx"},{title:"By"},{title:"Cx"}]}];

const filterByTitle = (search, arr) => 
  arr.map(
    ({data, ...rest}) => ({
        ...rest, 
        data: data.filter(({title}) => title.startsWith(search))
    })
  );
console.log(filterByTitle('B', list));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.