如何遍历嵌套对象的数组



我面临一个难题,我必须循环遍历一个嵌套对象(对象的对象)数组,该数组可能有其他对象和数组。也就是说,数组中的对象可以有其他对象和对象的数组,以此类推。

这个数据结构适用于一个列表(比如待办事项列表),它可以有另一个列表,而另一个列表可以有另一个列表,以此类推:

[
"Buy milk",
{ //<----------------- item 2 is is an object that represents sub-items
itemName: "Buy Meat", //<------------ name of item 2 on list
subList: [ //<------ sub-items with an item of items
"Beef", 
{
itemName: "Fish",
subList: ["Tilapia", "Catfish", "Monkfish", "Halibut"]
} ,
"Chicken",
],
},
"Buy cooking oil",
"Buy baking soda",
{ //<------------------- item 6 is an object that represents sub-items (sub-todo)
itemName: "Buy Vegetable", //<------------ name of item 6 on list
itemList: ["Cabbage", "Carrot", "Tomatoe", "Lettuce"] //<------ sub-items
},
"Buy bread"
]

如何在这样的数据结构上循环?还有,是否有更好的方法来表示这样的列表?

你问了两个问题:首先是结构

嵌套对象的结构应该是一致的,所以问题是如何创建父级和子级具有相同结构的嵌套对象。

不需要按照在屏幕上看到的方式来存储对象

class MyList {
constructor(itemName, subList) {
this.itemName = itemName;
this.subList = subList; // is always of Type MyList []
}
}

对于这个结构,如果SubList没有定义,它就是一个简单的字符串。

class MyList {
constructor(itemName, subList) {
this.itemName = itemName; // is name of list or individual item
this.subList = subList; // is always of Type MyList [] or undefined
}
}
let list = new MyList('Buy Meat', []); // ur sublist of buyMeat
list.subList.push(new MyList('beaf'));
let fishList = new MyList('fish', []); // sublist
fishList.subList.push(new MyList('Tilapia'));
fishList.subList.push(new MyList('Catfish'));
fishList.subList.push(new MyList('Monkfish'));
fishList.subList.push(new MyList('Halibut'));
list.subList.push(fishList);
list.subList.push(new MyList('chicken'));
console.log(list);
如何循环,现在,如果遵循这个结构,您将注意到每个MyList都可以被视为一个节点。您可以使用任何树遍历方法来访问所有元素。你想怎么做都行。下面的例子只是读取树的深度优先方法遍历。

class MyList {
constructor(itemName, subList) {
this.itemName = itemName; // is name of list or individual item
this.subList = subList; // is always of Type MyList [] or undefined
}
}
let list = new MyList('Buy Meat', []); // ur sublist of buyMeat
list.subList.push(new MyList('beaf'));
let fishList = new MyList('fish', []); // sublist
fishList.subList.push(new MyList('Tilapia'));
fishList.subList.push(new MyList('Catfish'));
fishList.subList.push(new MyList('Monkfish'));
fishList.subList.push(new MyList('Halibut'));
list.subList.push(fishList);
list.subList.push(new MyList('chicken'));
// Example reading all item name:
reader = (node) => node.subList ?  node.subList.map(reader).flat() : [node.itemName] 

console.log(reader(list))

最新更新