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.
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())
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')
The path info returned from resolvePath contains a few helpful methods.
info.fieldinfo.parent[info.fieldName] = newValuedelete on the parent. Same as delete info.parent[info.fieldName]The path info fields can also be accessed directly.
Set to true if the path can be resolved up to the parent.
An optional options object can be passed into the resolver.
resolve(object, 'my.path', options)
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
<script src="https://unpkg.com/js-path-resolver/dist/index.js"></script>
<script>
const resolver = jsPathResolver.default;
</script>
import resolver from 'js-path-resolver';