我有一个给出嵌套对象数组的数组。每个嵌套数组都具有“ 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
由于某种原因,我无法使“行”属性上的迭代部分起作用。如果您可以帮助我完成这一部分,我会自己解决其余的问题。
谢谢!
答案 0 :(得分:1)
您可以两次使用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);
答案 1 :(得分:1)
您需要使用javascript的forEach函数,该函数是数组成员函数
myTextBlock.forEach((obj) => {
// here you can access the row key from the obj
obj.row.forEach((textObj) => {
console.log(textObj);
}
}