希望检查 JSON 文件中是否存在像 objecta.objectb.objectc 这样的完整路径。第一个想法是对对象进行 JSON 解析,然后使用反射检查属性是否存在,但是当我按如下方式尝试时,它不允许我访问属性键中的子项?
我错过了什么?
const object1 = {
property1: 42,
property2 : {
property2a: "abc"
},
};
console.log(Reflect.has(object1, 'property1'));
// expected output: true
console.log(Reflect.has(object1, 'property2.property2a'));
// expected output: true but is false
console.log(object1.property2.property2a);
// prints value as expected
console.log(Reflect.has(object1, 'property3.property2a'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
// expected output: true
最佳答案
您不应该在此处使用Reflect
。相反,您应该使用多个条件语句来检查它是否存在,否则返回 false:
const object1 = {
property1: 42,
property2 : {
property2a: "abc"
},
};
console.log(object1 && object1.property2 && object1.property2.property2a ? true : false)
console.log(object1 && object1.property2 && object1.property2.property2b ? true : false)
关于javascript - 使用 Reflect ES6 获取子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56563963/