@yr/property

7.0.3 • Public • Published

NPM Version Build Status

Generic utility for getting/setting properties of an object. Supports namespaced properties of type foo/bar and simple immutability.

Usage

var property = require('@yr/property');
var obj = {
  foo: {
    bar: 'bar',
    bat: {
      foo: 'foo'
    }
  }
};

property.get(obj, 'foo/bar'); //=> 'bar'
property.set(obj, 'foo/baz', false);
property.get(obj, 'foo/baz'); //=> false
property.set(obj, 'foo/bat', { boo: 'boo' });
property.get(obj, 'foo/bat'); //=> { foo: 'foo', boo: 'boo' }

API

separator: character used to separate key segments (default is "/").

get(obj, key): retrieve value for key of obj. Keys can be namespaced (separated by exports.separator).

property.get(obj, 'foo/bar'); //=> 'bar'

set(obj, key, value, options): store value at key of obj. Keys can be namespaced (separated by exports.separator). Behaviour is configurable with the following options properties:

  • immutable: return a unique copy of obj with changes applied, leaving the original unmodified (default false)
  • merge: instead of overwriting, merge values if source and destination are objects (default true)

Note: When process.env.NODE_ENV != 'production' and options.immutable, the portion of the written, modified tree is deeply frozen with Object.freeze.

var obj = {};
property.set(obj, 'foo/baz/boo', false); //=> { foo: { baz: { boo: false } } }
property.set(obj, 'foo/baz/bat', 'bat'); //=> { foo: { baz: { boo: false, bat: 'bat' } } }
property.set(obj, 'foo/baz', 'baz', { merge: false }); //=> { foo: { baz:'baz' } }

var obj2 = property.set(obj, 'foo/bar', 'foo', { immutable: true });
console.log(obj === obj2); //=> false

reshape(obj, depth): reshape keys of obj so that they have a maximum length of depth.

// Flatten object with key depth of 1
var obj = {	a: { aa: 'aa' } };
var flat = property.reshape(obj, 2);
console.log(flat['a/aa']); //=> aa
// Unflatten object with key depth of 2
var unflat = property.reshape(flat, 1);
console.log(unflat.a); //=> { aa: 'aa' }

Package Sidebar

Install

npm i @yr/property

Weekly Downloads

21

Version

7.0.3

License

MIT

Last publish

Collaborators

  • yr
  • saegrov