components: any = [
{
id: "17:12610",
name: "custom-component",
hasWarning: true,
selectableKey: 'id',
preview: 'thumbnailLink',
children: {
"17:12610": {
"name": "cc-1",
"type": "instance",
"children": {
"7:43": {
"name": "icon-slot",
"children": {},
"type": "div"
}
}
}
}
}
];
Object.keys(this.components[0].children).forEach((res) => {
console.log(res);
});
我正在這樣迭代,但它只給了我第一個 ID。我想獲取每個孩子的 ID 和姓名。我還想跟蹤索引,以便我可以對特定索引進行更改
我想要這樣的輸出:
- 編號:17:12610 名稱:cc-1
- id : 7:43 name : 圖示槽
uj5u.com熱心網友回復:
您components[0]
在 forEach 函式之前指定。如果您的組件陣列中有多個元素,那么您將需要以下內容:
(this.components).forEach((root => {
(root.children).forEach((child) => {
console.log('id:' child ' name:' child.name);
}
}
);
此外,查看您的陣列構造,您創建了一個物件陣列,而不是鍵值對陣列,因此它們不會有與之關聯的鍵。如果您想要與它們關聯的鍵,請將您的物件 {} 更改為嵌套陣列 []。
您編輯了問題以添加所需的輸出格式。我相應地編輯了我的答案。
uj5u.com熱心網友回復:
let child = components[0].children;
while (child) {
const id = Object.keys(child)[0];
const name = child[id].name;
console.log('id: ' id ' name: ' name);
child = child[id].children;
}
uj5u.com熱心網友回復:
您可以創建一個遞回函式來實作解決方案。像這樣的東西:
const component = [{"id":"17:12610","name":"custom-component","hasWarning":true,"selectableKey":"id","preview":"thumbnailLink","children":{"17:12610":{"name":"cc-1","type":"instance","children":{"7:43":{"name":"icon-slot","children":{},"type":"div"}}}}}];
const recursive = (arr, formedArr=[]) => arr.reduce((a,e)=>{
Object.entries(e.children || e).forEach(([id, {name, children}])=>{
a.push({id, name});
if(children) recursive([children], a);
});
return a;
},formedArr);
console.log(recursive(component));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508318.html
標籤:javascript 数组 有角度的
上一篇:在操作之前洗掉元素