ES6如何更优雅地从对象数组中提取匹配ID数组的指定属性值
ES6简化实现方案
1. 常规简洁写法(最常用)
直接通过filter+map链式调用完成需求,无需声明多余中间变量,逻辑清晰易读:
const carriers = [ { id: 0, code: "gls" }, { id: 1, code: "tnt" }, { id: 2, code: "fedex" }, { id: 3, code: "ups" }, { id: 4, code: "postnl" }, ]; const active = [0, 2, 3]; // 直接链式调用,一步得到结果 const activeCode = carriers.filter(c => active.includes(c.id)).map(item => item.code); console.log(activeCode); // 输出 ["gls", "fedex", "ups"]
注:如果你的业务场景中
carriers的id可能是字符串类型的数字,可以保留Number(c.id)的转换,否则完全可以省略多余的类型转换操作。
2. 大数据量优化写法
如果active数组长度较大,Array.includes每次查询的时间复杂度为O(n),可以先转成Set将查询复杂度降低到O(1),提升性能:
const activeSet = new Set(active); const activeCode = carriers.filter(c => activeSet.has(c.id)).map(item => item.code);
3. 单次遍历最优性能写法
如果carriers数组本身长度也很大,可通过reduce仅遍历一次数组就完成筛选+取值,避免filter和map两次遍历的开销:
const activeCode = carriers.reduce((result, current) => { if (active.includes(current.id)) result.push(current.code); return result; }, []);
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

