检查给定 ID 是否存在于 JavaScript 的嵌套对象中的最佳方法是什么。
目的
campusElement = {
"id": "C1",
"name": "camp",
"buildings": [{
"id": "B1",
"name": "B-name",
"floors": [{
"id": "F1",
"name": "F-name",
"rooms": [{
"id": "R1",
"name": "R-name"
}]
}]
}]
}
目前我正在遍历整个对象并做
组件.ts
isIdExists(elementID: string) {
var isIdUnique = false;
if (campusElement.id === elementID) {
isIdUnique = true;
} else {
for (const building of campusElement.buildings) {
if (building.id === elementID) {
isIdUnique = true;
break;
} else {
for (const floor of building.floors) {
if (floor.id === elementID) {
isIdUnique = true;
break;
} else {
for (const room of floor.rooms) {
if (room.id === elementID) {
isIdUnique = true;
break;
}
}
}
}
}
}
}
return isIdUnique;
}
有一个更好的方法吗?