簡體   English   中英

使用嵌套數組對象迭代數組的屬性

[英]Iterate over property of array with nested array objects

我有一個包含嵌套對象數組的數組。 每個嵌套數組都有屬性“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 的 forEach 函數,它是一個數組成員函數

myTextBlock.forEach((obj) => {
    // here you can access the row key from the obj
    obj.row.forEach((textObj) => {
         console.log(textObj);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM