过滤包含对象数组的对象数组

时间:2020-07-21 06:48:31

标签: javascript arrays

我正在尝试过滤数组,但是我没有成功过滤对象内部的数组

我将举一个数组的例子:

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

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

预期结果

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

我尝试过的事情

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

我没有成功过滤对象内部的main ...

我该怎么做?

谢谢!

** 更新-当前解决方案

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

2 个答案:

答案 0 :(得分:1)

您可以通过重建对象来解决它:

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);

答案 1 :(得分:0)

如果您使用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)