使用 JavaScript 按键过滤嵌套对象
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/3 10:52:17
假设,我们有一个像这样的对象数组 −
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 } ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

