使用 JavaScript 的嵌套集合过滤器
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 22:04:17
假设,我们有一个像这样的嵌套对象数组 −
const arr = [{
id: 1,
legs:[{
carrierName:'Pegasus'
}]
},
{
id: 2,
legs:[{
carrierName: 'SunExpress'
},
{
carrierName: 'SunExpress'
}]
},
{
id: 3,
legs:[{
carrierName: 'Pegasus'
},
{
carrierName: 'SunExpress'
}]
}];
我们需要编写一个 JavaScript 函数,该函数将一个这样的数组作为第一个参数,将搜索查询字符串作为第二个参数。
我们的函数应该过滤数组以仅包含那些"承运人名称"为属性值与第二个参数指定的值相同。
如果对于上述数组,第二个参数是"Pegasus"。那么输出应该看起来像 −
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"
}
]
}
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

