javascript - 使用嵌套数组对象迭代数组的属性
问题描述
我有一个包含嵌套对象数组的数组。每个嵌套数组都有属性“row”:
myTextBlock=[
{ "row": [{text: "test1", category: 1}, {text: "test2", category: 2}, {text: "test3", category: 1}]},
{ "row": [{text: "test4", category: 2}, {text: "test5", category: 1}, {text: "test6", category: 3}]},
{ "row": [{text: "test7", category: 1}, {text: "test8", category: 3}, {text: "test9", category: 1}]}
];
我需要遍历嵌套的文本键(在保留顺序的同时连接字符串,在每一行之后添加一个换行符并在其间添加一个逗号)。
期望的结果:
test1 test2 test3 \n test4 test5 test6 \n test7 test8 test9
出于某种原因,我无法让属性“行”上的迭代部分起作用。如果你能在这部分帮助我,我会自己解决剩下的问题。
提前致谢!
解决方案
您可以使用array.reduce两次将两个数组级别转换为单个值:
let myTextBlock=[
{ "row": [{text: "test1", category: 1}, {text: "test2", category: 2}, {text: "test3", category: 1}]},
{ "row": [{text: "test4", category: 2}, {text: "test5", category: 1}, {text: "test6", category: 3}]},
{ "row": [{text: "test7", category: 1}, {text: "test8", category: 3}, {text: "test9", category: 1}]}
];
let result = myTextBlock.reduce((state, current) => {
return state +
current.row.reduce((st, cur) => st + cur.text + " ", "") +
"\n";
}, "");
console.log(result);
推荐阅读
- javascript - 如何解析 html 字符串并将其添加到 Angular 中的 DOM
- android - 之后我们将在 SpeechRecognizer 中获得 ERROR_TOO_MANY_REQUESTS 的大致限制是多少?
- python - 从 Python 中的元组中提取字符串
- google-sheets - VLOOKUP 匹配多个列
- python - 从文本文件中提取某些数据 - 字符串操作
- json - 如何从 JSONPlugin 中捕获错误
- javascript - 错误:“/app/node_modules/uuid”的包导出未定义有效的“。” 目标
- javascript - 试图写一个函数来写更少的代码
- python - 比较python中的打印语句
- bash - bash help - 为匹配模式的文件夹运行命令的脚本