UnderscoreJS如何扁平化嵌套属性?动态JSON数组处理需求
使用UnderscoreJS扁平化嵌套JSON数组提取指定字段
嘿,这需求不难搞定!用UnderscoreJS的话,咱们可以轻松实现你要的效果——把动态的嵌套JSON数组扁平化,只提取所有层级里的a字段。
核心实现思路
遍历数组里的每一个对象,分别提取外层的a字段和内层aa对象里的a字段,然后把这些单独的对象收集到一个新数组里就行。因为数组元素数量不固定,用Underscore的flatMap方法刚好合适,它能自动把迭代返回的子数组扁平化。
基础实现代码
// 你的动态数据数组 const dynamicData = [ { 'a': 1, 'b': 10, 'aa': { 'a': 11, 'ab': 110 } }, { 'a': 2, 'b': 20, 'aa': { 'a': 22, 'ab': 220 } }, { 'a': 3, 'b': 30, 'aa': { 'a': 33, 'ab': 330 } }, // 可以继续添加更多元素 ]; // 扁平化提取所有a字段 const flattenedResult = _.flatMap(dynamicData, item => [ { a: item.a }, { a: item.aa.a } ]); console.log(flattenedResult); // 输出结果:[{ 'a': 1}, { 'a': 11 }, { 'a': 2 }, { 'a': 22 }, { 'a': 3 }, { 'a': 33 }]
更健壮的版本(处理可能的缺失字段)
如果你的动态数据里可能存在没有aa字段,或者aa里没有a的情况,可以加个判断逻辑,避免报错:
const flattenedResult = _.flatMap(dynamicData, item => { const resultList = [{ a: item.a }]; // 检查aa字段是否存在且包含a属性 if (item.aa && typeof item.aa.a !== 'undefined') { resultList.push({ a: item.aa.a }); } return resultList; });
这样不管数组里有多少元素,都能完美输出你要的结构啦!
内容的提问来源于stack exchange,提问作者ConfusedDeveloper
相关产品推荐
相关产品推荐

