使用Node.js处理嵌套分类数组实现分类与子项单独成对输出
问题原因
你的原写法存在两个问题:
- 当前外层
arr是双层嵌套结构,每一个子元素才是你最初单组场景里的[分类名, 子项数组]结构,原写法只取了第二个分组的子项做处理,还错误把整个第一组数组当成了分类名 - 要实现每行单独输出,不能直接打印整个结果数组,需要逐行打印每个条目
实现方案
方案1:先聚合所有条目再逐行打印
用flatMap先把所有分类和子项映射为扁平化的二元组列表,再逐行输出:
const arr = [ ["product", ["car", "Bike", "truck"]], ["Milk", ["cheese", "butter", "curd"]], ["Animals", ["Lion", "Tiger"]] ]; // 生成所有[分类名, 子项]的扁平化列表 const allItems = arr.flatMap(([category, subItems]) => { // 可选:如果需要分类名首字母大写,把category替换为下面的写法 // const formattedCategory = category.charAt(0).toUpperCase() + category.slice(1); return subItems.map(item => [category, item]); }); // 逐行打印 allItems.forEach(item => console.log(item));
方案2:双层遍历直接打印
不需要生成中间数组,遍历过程中直接输出,内存占用更低:
const arr = [ ["product", ["car", "Bike", "truck"]], ["Milk", ["cheese", "butter", "curd"]], ["Animals", ["Lion", "Tiger"]] ]; for (const [category, subItems] of arr) { // 首字母大写处理可选 const formattedCategory = category.charAt(0).toUpperCase() + category.slice(1); for (const item of subItems) { console.log([formattedCategory, item]); } }
两种方案的输出都和你预期的格式完全一致。
内容的提问来源于stack exchange,提问作者Aakash
相关产品推荐
相关产品推荐

