希望在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发布于 2019-06-12 14:01:18
你不应该在这里使用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)
https://stackoverflow.com/questions/56563963
复制相似问题