过滤对象中不满足的项

如何根据数组来过滤对象中符合的数据
const arr = ['home1', 'home2', 'home3', 'home4']

const obj = [
  {
    children: [
      {
        name: 'home1'
      },
      {
        name: 'home5'
      }
    ]
  },
  {
    children: [
      {
        name: 'home6'
      }
    ]
  },
  {
    children: [
      {
        name: 'home3'
      }
    ]
  }
]

将不满足的数据过滤掉变成

[
  {
    children: [
      {
        name: 'home1'
      }
    ]
  },
  {
    children: [
      {
        name: 'home3'
      }
    ]
  }
]

望采纳!!!点击回答右侧采纳即可!

可以使用 Array.prototype.filter() 方法来过滤对象中符合的数据:


const array = [1, 2, 3];
const obj = {
  a: 1,
  b: 2,
  c: 3
};
const filteredObj = Object.keys(obj).filter(key => array.includes(obj[key])).reduce((acc, key) => {
  acc[key] = obj[key];
  return acc;
}, {});
console.log(filteredObj);
// { a: 1, b: 2, c: 3 }