在JavaScript中过滤对象数组
假设我们分别有两个文字和对象数组-
const source = [1, 2, 3 , 4 , 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];我们需要编写一个包含这两个数组的JavaScript函数。我们的函数应该创建一个新数组,其中包含对象数组中所有包含这些元素的元素,这些对象的“city”键值存在于文字数组中。
示例
让我们写代码-
const source = [1, 2, 3 , 4 , 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];
const filterByLiterals = (objArr, literalArr) => {
const common = objArr.filter(el => {
return literalArr.includes(el['city']);
});
return common;
};
console.log(filterByLiterals(cities, source));输出结果
控制台中的输出将是-
[ { city: 4 } ]热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短