1

检查给定 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;
}

有一个更好的方法吗?

4

2 回答 2

2

“最佳”是主观的,但您可以编写一个通用递归函数来查找具有指定名称和值的属性,如果在顶层找不到它,则遍历所有属性以检查任何数组和如果是这样,递归地检查每个数组元素:

function propertyExists(obj, propName, propValue) {
  if (obj[propName] === propValue)
    return true
  
  for (var k in obj) {
    if (Array.isArray(obj[k]) && obj[k].some(function(v) {
        return typeof v === "object" && propertyExists(v, propName, propValue)
      })) {
        return true
    }
  }
  return false
}

campusElement = {
        "id": "C1",
        "name": "camp",
        "buildings": [{
            "id": "B1",
            "name": "B-name",
            "floors": [{
                "id": "F1",
                "name": "F-name",
                "rooms": [{
                    "id": "R1",
                    "name": "R-name"
                }]
            }]
        }]
    }
    
console.log(propertyExists(campusElement, "id", "C1"))                    // true
console.log(propertyExists(campusElement, "id", "R1"))                    // true
console.log(propertyExists(campusElement, "name", "R-name"))              // true
console.log(propertyExists(campusElement, "id", "no matching value"))     // false
console.log(propertyExists(campusElement, "no matching prop name", "C1")) // false
console.log(propertyExists(campusElement, "rooms", "X1"))                 // false

于 2017-04-04T04:08:55.640 回答
1

现在我正在使用 java 脚本“包含”来执行此操作

findIfIdExists(object, key, value){
   return JSON.stringify(object).includes('"'+key+'":"'+value+'"');
}

console.log(findIfIdExists(campusElement, 'id', 'C1')); //true
于 2017-04-04T04:19:43.170 回答