实现类似lodash.get无需指定数组索引的对象路径遍历取值函数
自动遍历数组的路径取值函数实现
该函数和lodash的_.get()核心区别为:无需在路径中指定数组索引(如abc.xyz[0]),遇到路径节点为数组时会自动遍历所有元素,最终聚合返回所有匹配路径的对应值。
完整实现代码
function accumulateValues(obj, path) { const keys = path.split('.'); let resultPool = [obj]; for (const key of keys) { const nextPool = []; for (const item of resultPool) { if (item == null) continue; if (Array.isArray(item)) { item.forEach(subItem => { if (subItem?.[key] !== undefined) { nextPool.push(subItem[key]); } }); } else { if (item[key] !== undefined) { nextPool.push(item[key]); } } } resultPool = nextPool; if (resultPool.length === 0) break; } // 拍平所有层级的嵌套数组,返回一维结果 return resultPool.flat(Infinity); }
使用示例
示例1
const _object = {abc: {xyz: [{value: 1}, {value: 2}]}}; console.log(accumulateValues(_object, 'abc.xyz')); // 输出: [{value: 1}, {value: 2}] console.log(accumulateValues(_object, 'abc.xyz.value')); // 输出: [1, 2]
示例2
const _object = {abc: [{xyz: [{values: 1}]}]}; console.log(accumulateValues(_object, 'abc.xyz.values')); // 输出: [1]
内容的提问来源于stack exchange,提问作者Giannos Charalambous
相关产品推荐
相关产品推荐

