Home > other >  React : filter get value from array of objects with specific key and group result into array
React : filter get value from array of objects with specific key and group result into array

Time:07-26

I have an array of objects which has a structure like this

[
  {
    title : 'Some title 1' , 
    newList: [{list: 'list 1', isCheck: true},{list: 'list 2', isCheck: false}]
  },
  {
    title : 'Some title 2' , 
    newList: [{list: 'list 2.1', isCheck: true}, {list: 'list 2.2', isCheck: false}
  },
  {
    title : 'Some title 3' , 
    newList: [{list: 'list 3.1', isCheck: false}, {list: 'list 3.2', isCheck: false}
  },
 ...
]

so I want to take a list value where isCheck is true and group them into an array.

I've tried using the following filter function

let data = stateDataListTask.map(el => {
   return el.newList.filter(sub=> sub.isCheck === true);
});

but the problem is that the returned value is not just 'list' value and and some empty array when using filter

[[{list: 'list 1', isCheck: true}],[],[{list: 'list 3', isCheck: true}],[],[],[]]

so how do i just take the list data and group them into an array

CodePudding user response:

You just need to use a flat map to flatten the array

stateDataListTask.flatMap(({ newList }) => newList.filter((list) => list.isCheck)).map(el => {
    return el.list;
  });

Also converting a boolean to a boolean is redundant

sub.isCheck === true // Don't do this

CodePudding user response:

as i understand U need a filtered list that contain true isChecked item. isnt it.

checkout this code for filtering data:

let data = stateDataListTask.filter(el => el.newList["isCheck"]);
  • Related