如何将包含children字段的对象数组转换为索引匹配的二维数组
实现方案
你可以通过数组的map方法按索引配对元素实现转换,以下是两种可用的写法:
1. 适配当前场景的简易写法
如果你的list固定只有水果、蔬菜两个分类,直接提取两个children数组按索引配对即可:
const list = [ { id: 5844, option: 'fruit', children: ['apple', 'banana', 'pear'] }, { id: 5845, option: 'vegetables', children: ['tomato', 'potato', 'spinach'] } ] // 提取两个子数组 const [fruitList, vegetableList] = list.map(item => item.children) // 按索引配对 const result = fruitList.map((fruitItem, index) => [fruitItem, vegetableList[index]]) console.log(result) // 输出 [['apple', 'tomato'], ['banana', 'potato'], ['pear', 'spinach']]
2. 通用场景写法
如果后续可能新增更多分类(比如新增零食、肉类等分类,所有分类的children长度一致),可以用更通用的写法,不需要手动拆分分类:
// 以第一个分类的children长度为基准遍历索引,每个索引下取出所有分类对应位置的元素 const result = list[0].children.map((_, index) => list.map(item => item.children[index]))
注意:两种写法都要求所有分类的children数组长度一致,如果存在长度不一致的情况,短数组对应索引位置会返回undefined,可以根据需求补充长度校验逻辑。
内容的提问来源于stack exchange,提问作者nianyu
相关产品推荐
相关产品推荐

