如何用JavaScript及Lodash提取嵌套JSON数组中的用户数据为单级数组?
提取嵌套数组中的用户对象(原生JS + Lodash实现)
先提个小细节:你给出的原始数据里,数组内的单个对象重复定义了id属性——在JavaScript中后面的id:2会覆盖前面的id:1,最终这个对象的id值是2,但这并不影响我们提取users数组的需求。
下面给你整理两种实用的实现方案,适配不同的项目环境:
一、原生JavaScript实现
原生JS现在有很多便捷的数组方法可以处理这类嵌套合并场景,推荐两种常用写法:
1. 使用flatMap(ES2019及以上版本支持)
flatMap相当于map+flat的组合,先对数组每个元素做映射,再自动把结果扁平化一层,完美适配这个需求:
const data = [{id:1, users:[{name:'john'}, {name:'smith'}, {name:'frank'}], id:2, users:[{name:'lary'}, {name:'steve'}, {name:'joe'}]}]; const allUsers = data.flatMap(item => item.users); console.log(allUsers); // 输出:[{name:'john'}, {name:'smith'}, {name:'frank'}, {name:'lary'}, {name:'steve'}, {name:'joe'}]
2. 使用reduce + concat(兼容低版本ES)
如果你的项目需要兼容ES2019之前的环境,用reduce累加合并是更稳妥的选择:
const data = [{id:1, users:[{name:'john'}, {name:'smith'}, {name:'frank'}], id:2, users:[{name:'lary'}, {name:'steve'}, {name:'joe'}]}]; const allUsers = data.reduce((accumulator, currentItem) => { return accumulator.concat(currentItem.users); }, []); console.log(allUsers); // 输出和上面一致
我们从空数组开始,每次把当前对象的users数组拼接到累加器中,最终得到合并后的单级数组。
二、Lodash实现
如果你的项目已经引入了Lodash,写法会更简洁,它提供了专门的工具方法处理这类数组操作:
1. 使用_.flatMap
Lodash的flatMap支持直接指定要提取的属性名,一行代码就能搞定:
const _ = require('lodash'); // Node环境引入,浏览器环境可通过CDN加载 const data = [{id:1, users:[{name:'john'}, {name:'smith'}, {name:'frank'}], id:2, users:[{name:'lary'}, {name:'steve'}, {name:'joe'}]}]; const allUsers = _.flatMap(data, 'users'); console.log(allUsers);
2. 使用_.map + _.flatten
也可以先提取所有users数组,再做扁平化处理:
const _ = require('lodash'); const data = [{id:1, users:[{name:'john'}, {name:'smith'}, {name:'frank'}], id:2, users:[{name:'lary'}, {name:'steve'}, {name:'joe'}]}]; const allUsers = _.flatten(_.map(data, 'users')); console.log(allUsers);
先通过_.map拿到包含所有users数组的二维数组,再用_.flatten将其转换为单级数组。
内容的提问来源于stack exchange,提问作者Venkatesh Vellingiri
相关产品推荐
相关产品推荐

