使用 JavaScript 筛选嵌套对象中的键


假设我们有一个这样的对象数组 −

const arr = [{ 'title': 'Hey',
   'foo': 2,
   'bar': 3
}, {
   'title': 'Sup',
   'foo': 3,
   'bar': 4
}, {
   'title': 'Remove',
   'foo': 3,
   'bar': 4
}];

我们需要编写一个 JavaScript 函数,该函数将一个这样的数组作为第一个输入,并将一个字符串文字数组作为第二个输入。

然后,我们的函数应该准备一个新数组,其中包含所有那些其 title 属性部分或全部包含在第二个文字数组中的对象。

示例

代码如下 −

const arr = [{ 'title': 'Hey',
   'foo': 2,
   'bar': 3
}, {
   'title': 'Sup',
   'foo': 3,
   'bar': 4
}, {
   'title': 'Remove',
   'foo': 3,
   'bar': 4
}];
const filterTitles = ['He', 'Su'];
const filterByTitle = (arr = [], titles = []) => {
   let res = [];
   res = arr.filter(obj => {
      const { title } = obj;
      return !!titles.find(el => title.includes(el));
   });
   return res;
};
console.log(filterByTitle(arr, filterTitles));

输出

控制台中的输出如下 −

[ { title: 'Hey', foo: 2, bar: 3 }, { title: 'Sup', foo: 3, bar: 4 } ]

更新时间:23-Nov-2020

902 次浏览

开启你的职业生涯

完成课程以获得资格认证

开始学习
广告
© . All rights reserved.