使用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 } ]热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短