使用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" } ] } ]