You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现类似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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:54:03