简体   繁体   中英

filter array of object which contains array of objects by an array

I`m trying to filter an array but I don t succeed to filter array inside the object

I will give us an example of how the array is:

const data = [
   {
    path: 'data1',
    main: [
       {
        path: 'mainData11'
       },
       {
        path: 'mainData12'
       }
     ]
   },
   {
    path: 'data2',
    main: [
       {
        path: 'mainData21'
       },
       {
        path: 'mainData22'
       }
     ]
   }
];

const filterArray = ['data1', 'mainData12'];

expected result

const data = [
 {
  path: 'data1'
  main: [
   {
    path: 'mainData12' 
   }
  ]
 }
]

What I`ve tried

data.filter(el => filterArray.includes(el.path))

I did not succeed to filter the main inside object...

How I do that?

Thanks!

** UPDATE -- CURRENT SOLUTION

data.reduce((results, item) => {
 if(filterArray.some(f => item.path === f)){
  results.push(
   {
    ...item,
    path: item.path,
    main: item.main.filter(i => filterArray.some(f => i.path === f))
   }
  )
 };
 return results;
}, []);

You can solve it by rebuilding the object:

 const data = [{ path: 'data1', main: [{ path: 'mainData11', }, { path: 'mainData12', }, ], }, { path: 'data2', main: [{ path: 'mainData21', }, { path: 'mainData22', }, ], }, ]; const filterArray = ['data1', 'mainData12']; const filteredData = data.filter(entry => entry.path === filterArray[0]).map(entry => ({ path: entry.path, main: entry.main.filter(x => x.path === filterArray[1]), })).filter(entry => entry.main.length); console.log(filteredData);

This can be done in one step if you use a reduce

 const data = [ { path: 'data1', main: [ { path: 'mainData11' }, { path: 'mainData12' } ] }, { path: 'data2', main: [ { path: 'mainData21' }, { path: 'mainData22' } ] } ]; const filterArray = ['data1', 'mainData12']; const results = data.reduce((results, item) => { if (filterArray.some(f => item.path === f) && item.main.some(i => filterArray.some(f => i.path === f))) { results.push( { path: item.path, main: item.main.filter(i => filterArray.some(f => i.path === f)) } ); } return results; }, []); console.log(results)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM