Ramon Medeiros
Ramon Medeiros

Reputation: 2641

javascript: Check multiple nested properties on a Json

I have a JSON that I want to check if has the following properties:

json.prop1.prop2.prop3

This method can check a property: json.hasOwnProperty("prop1")

Is there something that I can use to check all the prop1,prop2,prop3 at the same time?

Upvotes: 0

Views: 84

Answers (3)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2806

json["prop1"]["prop2"]["prop3"] or used json?.prop1?.prop2?.prop3

Upvotes: -1

Jay
Jay

Reputation: 3117

You can also use lodash get function to check nested object

https://lodash.com/docs/4.17.15#get

const json = {
  prop1: {
    prop2: {
      prop3: "you are here"
    }
  }
}

console.log(_.get(json, "prop1.prop2.prop3"));
console.log(_.get(json, "prop1.prop3.prop3"));
console.log(_.get(json, "prop1.prop3.prop3", "Default value"));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 0

Pushkin
Pushkin

Reputation: 3604

With Babel Optional Chaining plugin you can do this

 json?.prop1?.prop2?.prop3 

This is similar to

 json && json.prop1 && json.prop1.props2 && json.prop1.props2.prop3 

Example of using Optional Chaining

const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined

// Optional chaining and normal chaining can be intermixed
obj?.foo.bar?.baz; // Only access `foo` if `obj` exists, and `baz` if
                   // `bar` exists

// Example usage with bracket notation:
obj?.['foo']?.bar?.baz // 42

Upvotes: 2

Related Questions