@pdz/op
v1.1.6
Published
Simple object manipulation by path
Downloads
1
Readme
A small set of universal functions for working with objects, using dot-separated path strings.
Example:
'use strict';
const pdzOP = require('@pdz/op');
const log = (...args) => {
console.log.apply(null, args.map(el => typeof(el) !== 'string' ? JSON.stringify(el) : el));
}
// Static style
{
const test = { a: { b: { c: 123 }, d: { e: 456 } } }
log('Get 0', test);
// Get 0 {"a":{"b":{"c":123},"d":{"e":456}}}
log('Get 1:', pdzOP.get(test, 'a.b.c'));
// Get 1: 123
log('Get 2:', pdzOP.get(test, ['a.b.c', 'a.b', 'x.y.z']));
// Get 2: {"a.b.c":123,"a.b":{"c":123}}
}
{
const test = { a: { b: { c: 123 }, d: { e: 456 } } }
log('Set 0', test);
// Set 0 {"a":{"b":{"c":123},"d":{"e":456}}}
log('Set 1:', pdzOP.set(test, 'a.b.c', 789));
// Set 1: {"a":{"b":{"c":789},"d":{"e":456}}}
log('Set 2:', pdzOP.set(test, { 'a.b.c': 789, 'a.f': 987 }));
// Set 2: {"a":{"b":{"c":789},"d":{"e":456},"f":987}}
log('Set 3:', pdzOP.set(test, ['a.b.c', 'a.d.e', 'a.f'], { g: 1 }));
// Set 3: {"a":{"b":{"c":{"g":1}},"d":{"e":{"g":1}},"f":{"g":1}}}
}
{
const test = { a: { b: { c: 123 }, d: { e: 456 } } }
log('Assign 0', test);
// Assign 0 {"a":{"b":{"c":123},"d":{"e":456}}}
log('Assign 1:', pdzOP.assign(test, 'a.b', { c2: 789 }));
// Assign 1: {"a":{"b":{"c":123,"c2":789},"d":{"e":456}}}
log('Assign 2:', pdzOP.assign(test, { 'a.b': { c2: 789 }, 'a.d': { e2: 987 } }));
// Assign 2: {"a":{"b":{"c":123,"c2":789},"d":{"e":456,"e2":987}}}
log('Assign 3:', pdzOP.assign(test, ['a.b', 'a.d'], { f: 654 }));
// Assign 3: {"a":{"b":{"c":123,"c2":789,"f":654},"d":{"e":456,"e2":987,"f":654}}}
}
{
const test = { a: { b: { c: 123 }, d: { e: 456 } } }
log('Del 0', test);
// Del 0 {"a":{"b":{"c":123},"d":{"e":456}}}
log('Del 1:', pdzOP.del(test, 'a.b.c'));
// Del 1: {"a":{"b":{},"d":{"e":456}}}
log('Del 2:', pdzOP.del(test, ['a.b.c', 'a.d']));
// Del 2: {"a":{"b":{}}}
}
// Object style
{
const test = { a: { b: { c: 123 }, d: { e: 456 } } }
const ob = new pdzOP(test, { separator: '>' });
log('OB 1:', ob.get('a>b>c'));
// OB 1: 123
log('OB 2:', ob.get(['a>b>c', 'a>b', 'x>y>z']));
// OB 2: {"a>b>c":123,"a>b":{"c":123}}
log('OB 3:', ob.set('a>b>c', 789));
// OB 3: {"a":{"b":{"c":789},"d":{"e":456}}}
// ... and any static method without first argument can be used on object.
}
Change global separator for static style:
pdzOP.separator = '>'; // Is global, default is '.'