如何获取多层嵌套动态键对象中各数组的长度?
解决多层嵌套对象数组转长度的问题
可以利用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
相关产品推荐
相关产品推荐

