Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading