object-doctor
Safe, Nested Property Access and Object Manipulation in JS.
object-doctor allows you to safely access and create nested properties and values.
Installation
npm install object-doctor
Usage
'use strict'; const dr = ;
dr.get(obj, path [, options])
Gets the value of a property at path
, returns the value if found, otherwise undefined
. Use options.default
to specify a default return value. options.delimiter
to specify a custom delimiter.
const obj = a: b: c: 'foo' // Access nested propertylet value = dr;console; // foo // Access undefined propertyvalue = dr;console; // undefined // Access property on undefinedvalue = dr;console; // undefined // Return some default valuevalue = dr;console; // '' // Using a custom delimitervalue = dr;console; // foo
dr.set(obj, path, value [, options])
Traverse a path
on an object and set a value
.
const obj = {}; dr;console; // { a: { b: { c: 'foo' } } }
By default, dr.set()
will not override existing property values. However, it will set new properties on non-primitive types such as objects, arrays, functions, etc. To override this behavior, use options.force = true
.
dr;console; // { a: { b: { c: 'foo' } } } dr;console; // { a: { b: { c: 'bar' } } }
dr.Context(obj [, options]) Class
Create a new dr object with persistent settings and method chaining.
const context = {} force: true ;
Constructor optionally accepts a JSON string as it's first argument.
const context = '{"a": {"b": "foo"}}';
dr.Context.prototype.get(path [, options]);
const obj = a: b: c: 'foo' const context = obj; const foo = context;console; // foo const bar = context;console; // ''
dr.Context.prototype.set(path, value[, options]);
set()
method can be chained when using a context object.
const context = {} force: true ; context; // Use context.get() to get the manipulated object back outlet transformed = context; console; // { a: { b: { c: 'bar', d: 'baz' } } }