使用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 官宣新年祝福语简短