Object.hasPath()

Test if an Object has a property.

Signature

Object.hasPath(Object: { *: Any }, path: Array<String>) => Boolean

Description

Object.hasPath() tests if an Object contains a property based on a provided path.

The path is defined as an Array of Strings, where each String represents a property key in the Object’s hierarchy. The method traverses the Object structure following the path to search for the property.

Parameters

Parameter Type Required Description

object

Object containing fields of Any type.

Yes

Object to test for a property.

path

Array of Strings

Yes

Path to an Object property. Each element in the Array represents a level in the Object’s hierarchy.

Return value

Type Description

Boolean

If true, the Object contains the property.

Examples

Basic example

// Test if the Object contains the top-level `foo` property.
Object.hasPath({ foo : 'bar' }, ['foo'])
true

Property that doesn’t exist

// Test if the Object contains the top-level `baz` property.
Object.hasPath({ foo : 'bar' }, ['baz'])
false

Nested property

// Defines an Object with customer data.
let customer =  {
  "name": "Ruby Von Rails",
  "email": "ruby@example.com",
  "address": {
    "street": "87856 Mendota Court",
    "city": "Washington",
    "state": "DC",
    "postalCode": "20220",
    "country": "US"
  }
}

// Test if the customer Object contains the
// nested `address.state` property.
Object.hasPath(customer, ['address', 'state'])
true

Nested property that doesn’t exist

// Defines an Object with customer data.
let customer =  {
  "name": "Ruby Von Rails",
  "email": "ruby@example.com",
  "address": {
    "street": "87856 Mendota Court",
    "city": "Washington",
    "state": "DC",
    "postalCode": "20220",
    "country": "US"
  }
}

// Test if the customer Object contains the
// nested `address.zipCode` property.
Object.hasPath(customer, ['address', 'zipCode'])
false

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!