0

Was hoping to check for existence of a full path like objecta.objectb.objectc in a JSON file. First idea had been to JSON parse to an object then use reflection check if property existed but when I try it as below it won't allow me to access a child in the property key?

What am I missing?

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
PatrickWalker
  • 550
  • 5
  • 19

1 Answers1

2

You shouldn't use Reflect here. Rather, you should use multiple conditional statements to check if it exists, else return 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)
Kobe
  • 6,226
  • 1
  • 14
  • 35