set-from-path
JS library to help you set values in nested objects using a string '.' separated path indicating the different keys to be accessed along the way.
It also exports a get function to get properties with the same notation
Examples
// Defaults to throwing when intermediate paths are not valid// (non-existent or primitives) var set = set var a = {} //> { b: 1 } //> { b: 1, c: {} } //> { b: 1, c: { a: 1 } } //> { b: 1, c: { a: 1, b: [] } } //> { b: 1, c: { a: 1, b: [ 1 ] } } //> { b: 1, c: { a: 1, b: [ 1, { d: 1 } ] } } //> { b: 1, c: { a: 1, b: [ 1, { d: 2 } ] } } //> Error: Couldn't set b.c in {"b":1,"c":{"a" ... //> Error: Couldn't set a.c in {"b":1,"c":{"a" ... // Also exports a setp that creates intermediate non existing paths as objects// Similar in spirit to mkdir and mkdirp var setp = setpvar b = b: 1 c: d: 2 ;; //> { b: 1, c: { d: { a: 1 } } }var c = a: a: 1 ;; //> { a: { a: 1 }, b: { c: 1 } }; //> { a: { a: 1, c: { d: 1 } }, b: { c: 1 } } // You get the idea... // There is also a get function that works the same way var get = get var a = b: 1 c: d: 2 e: 3 f: 5 2 ; //> undefined //> 1 //> undefined //> 2 //> 3 //> {f:5} //> 5
Usage
npm install --save set-from-path
Upgrade
1.0 to 2.0
All functions are exported from the module as methods. Before, the exports was
the set
function, but in 2.0 exports is just an object with the
functions on it, so:
Change in your code:
** 1.0 **
var set =
** 2.0 **
var set = set
The rest remains the same (.setp
or .set
).
get
was added to 2.0.