js-path-resolver

js-path-resolver is an NPM module for accessing Javascript objects using a string path. It also provides tools to get, set, replace, or remove resolved items.

You can download the package on npm.

Describing Paths

Let's start with how to describe a path to traverse a Javascript object.

A path uses dots to traverse objects and arrays within a Javascript object. Arrays can be traversed using braces foo[2] or dots foo.2.

const state = {
  lists: {
    todo: [
      {caption: 'wake up', completed: true},
      {caption: 'eat', completed: false},
    ]
  }
}

To get the completed value of the eat todo, we would use the path lists.todo.1.completed or lists.todo[1].completed.

The path object returned from resolvePath contains the field, the parent object or array, the fieldname, and an array of fieldNames.

This info descriptor allows us to get, set, replace, or remove the resolved item. resolvePath will return undefined if the path is not found or not defined in it's parent. It will throw an Error if the parent path is not found.

import resolvePath from 'resolve-path'
const info = resolvePath(state, 'lists.todo.1')
console.log(info.get())

Special Characters

To use ., [, ], or \ as a property name path, you will need to escape them using \ in your query.

// This will resolve to state['mr.dot']['odd[name']
const info = resolvePath(state, 'mr\.dot.odd\[name')

Using The Path Info

Actions

The path info returned from resolvePath contains a few helpful methods.

get()
Returns the field. Same as info.field
set(newValue)
Replaces the field with the newValue. Same as info.parent[info.fieldName] = newValue
delete()
Removes the field by calling delete on the parent. Same as delete info.parent[info.fieldName]

Info Fields

The path info fields can also be accessed directly.

field
The field, or undefined
parent
The parent object or array
fieldName
The name of the field
fieldNames
An array of field names leading up to the path, starting from the root object.
exists:boolean

Set to true if the path can be resolved up to the parent.

Options

An optional options object can be passed into the resolver. resolve(object, 'my.path', options)

options.onError

By default, if a path cannot be resolved up to the parent, an exception will be thrown.

resolver(state, 'foo') // will not throw
resolver(state, 'foo.bar') // will throw

To never throw while resolving, use the onError option. The property exists will be set to false instead. However, all mutation operations (delete, get, set) will throw.

const info = resolver(state, 'foo.bar', {onError:'continue'}) // will not throw
// info.exists === false
info.get() // will throw

Usage

Web Browser

<script src="https://unpkg.com/js-path-resolver/dist/index.js"></script>
<script>
const resolver = jsPathResolver.default;
</script>

Node

import resolver from  'js-path-resolver';