I have an array with nested object arrays given. Each nested array has the property "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}]}
];
I need to iterate over the nested text-key (to concatenate the string while preserving the order, adding a linebreak after every row and adding a comma in between).
Desired outcome:
test1 test2 test3 \n test4 test5 test6 \n test7 test8 test9
For some reason I can't get the iteration part over the property "row" to work. If you could help me with this part I would work the rest out myself.
Thanks in advance!
You can use array.reduce twice to convert both array levels into single value:
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);
You need to use forEach function of javascript which is an array member function
myTextBlock.forEach((obj) => {
// here you can access the row key from the obj
obj.row.forEach((textObj) => {
console.log(textObj);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.