如何扁平化嵌套对象数组,生成含name与label的新数组?
问题描述
给定如下数据结构:
[ { "models":[ { "name":"xyz", "options":[ { "label":"blue" }, { "label":"brown" } ] }, { "name":"abc", "options":[ { "label":"yellow" } ] }, { "name":"def", "options":[ { "label":"green" } ] } ] } ]
需要将其转换为包含所有name与label组合的数组,格式如下:
['xyz: blue', 'xyz: brown', 'abc: yellow','def: green']
一、完善Array.reduce实现
基于你提供的框架,核心逻辑是遍历每个model,将其name与每个option的label拼接后合并到累加器数组:
// 先从原始数据中提取models数组 const data = [/* 你的原始数据 */]; const models = data[0].models; const flat = (acc, current) => { // 生成当前model对应的所有name-label组合字符串 const combinations = current.options.map(option => `${current.name}: ${option.label}`); // 将新组合合并到累加器,返回新数组 return [...acc, ...combinations]; }; const result = models.reduce(flat, []); console.log(result);
二、RxJS实现方案
利用RxJS的数据流操作符完成扁平化与格式转换:
import { from } from 'rxjs'; import { mergeMap, map, toArray } from 'rxjs/operators'; const data = [/* 你的原始数据 */]; const models = data[0].models; from(models).pipe( // 扁平化每个model的options,展开为单个option的数据流 mergeMap(model => from(model.options).pipe( // 拼接name与label为目标格式 map(option => `${model.name}: ${option.label}`) )), // 将所有流中的结果收集为一个数组 toArray() ).subscribe(result => { console.log(result); });
内容的提问来源于stack exchange,提问作者RDK
相关产品推荐
相关产品推荐

