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

如何获取多层嵌套动态键对象中各数组的长度?

解决多层嵌套对象数组转长度的问题

可以利用Lodash的_.mapValues方法实现,它专门用来遍历对象的键值对并返回新对象,完美适配你这种两层嵌套的动态键结构:

const _ = require('lodash');

const input = {
  "a": {
    "deptAS": [{}],
    "deptDr": [{}, {}, {}, {}, {}, {}],
    "deptES": [{}, {}],
    "deptGW": [{}]
  },
  "b": {
    "deptDr": [{}, {}, {}, {}, {}],
    "deptES": [{}, {}, {}, {}],
    "deptLU": [{}, {}],
    "deptSR": [{}, {}]
  }
};

const result = _.mapValues(input, (innerObj) => 
  _.mapValues(innerObj, (arr) => arr.length)
);

console.log(result);

代码说明

  • 外层_.mapValues遍历最外层的a、b等键,对每个内层部门组对象进行处理
  • 内层_.mapValues遍历每个部门组里的数组键,将对应数组直接替换为其length属性值
  • 这是纯函数实现,不会修改原输入对象,返回的是符合要求的新对象

运行后输出结果完全匹配你的期望结构:

{
  "a": {
    "deptAS": 1,
    "deptDr": 6,
    "deptES": 2,
    "deptGW": 1
  },
  "b": {
    "deptDr": 5,
    "deptES": 4,
    "deptLU": 2,
    "deptSR": 2
  }
}

内容的提问来源于stack exchange,提问作者wclweb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:30:47