使用JavaScript的嵌套集合过滤器
假设我们有一个像这样的嵌套对象数组-
const arr = [{
id: 1,
legs:[{
carrierName:'Pegasus'
}]
},
{
id: 2,
legs:[{
carrierName: 'SunExpress'
},
{
carrierName: 'SunExpress'
}]
},
{
id: 3,
legs:[{
carrierName: 'Pegasus'
},
{
carrierName: 'SunExpress'
}]
}];我们需要编写一个JavaScript函数,该函数将一个数组作为第一个参数,并将搜索查询字符串作为第二个参数。
我们的函数应该过滤数组,使其仅包含“载体名称”属性值与第二个参数指定的值相同的那些对象。
如果对于上述数组,则第二个参数为“飞马座”。然后输出应该看起来像-
const output = [{
id: 1,
legs:[{
carrierName:'Pegasus'
}]
},
{
id: 3,
legs:[{
carrierName: 'Pegasus'
},
{
carrierName: 'SunExpress'
}]
}];示例
为此的代码将是-
const arr = [{
id: 1,
legs:[{
carrierName:'Pegasus'
}]
},
{
id: 2,
legs:[{
carrierName: 'SunExpress'
},
{
carrierName: 'SunExpress'
}]
},
{
id: 3,
legs:[{
carrierName: 'Pegasus'
},
{
carrierName: 'SunExpress'
}]
}];
const keys = ['Pegasus'];
const filterByKeys = (arr = [], keys = []) => {
const res = arr.filter(function(item) {
const thisObj = this;
return item.legs.some(leg => {
return thisObj[leg.carrierName];
});
}, keys.reduce((acc, val) => {
acc[val] = true;
return acc;
}, Object.create(null)));
return res;
}
console.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4));输出结果
控制台中的输出将是-
[
{
"id": 1,
"legs": [
{
"carrierName": "Pegasus"
}
]
},
{
"id": 3,
"legs": [
{
"carrierName": "Pegasus"
},
{
"carrierName": "SunExpress"
}
]
}
]热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志