javascript - 使用嵌套数组对象迭代数组的属性

标签 javascript json angular typescript

我有一个包含给定嵌套对象数组的数组。每个嵌套数组都有属性“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 - 使用嵌套数组对象迭代数组的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59222965/

相关文章:

http - 如何在 Angular 2 中正确设置 Http 请求 header

javascript - Vue.js 试图通过计算中的 ID 获取 DOM 元素返回 null

javascript - GWT 中是否有任何通知将要下载哪个片段

javascript - 如何使用 SoundJS 切换播放/暂停?

javascript - Aurelia PHP Post 请求为空 $_POST

angular - 根据时区更改 mat-datepicker 选择的日期值

angular - 尽管通过了审核,但 pwa 无法通过 chrome 安装

javascript - 在 Immutable.JS 的上下文中, "dense"是什么意思?

json - 如何在 JMeter 中提取完整的 JSON 响应数据?

php - 无法将 swift 应用程序连接到 MySQL