7.0.3 • Published 8 years ago

@yr/property v7.0.3

Weekly downloads
9
License
MIT
Repository
github
Last release
8 years ago

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' }
7.0.3

8 years ago

7.0.2

8 years ago

7.0.1

8 years ago

7.0.0

8 years ago

6.0.0

8 years ago

5.2.0

9 years ago

5.1.1

9 years ago

5.1.0

9 years ago

5.0.1

9 years ago

5.0.0

9 years ago

4.0.0

9 years ago

3.1.5

9 years ago

3.1.4

9 years ago

3.1.3

10 years ago

3.1.2

10 years ago

3.1.1

10 years ago

3.1.0

10 years ago

3.0.1

10 years ago

3.0.0

10 years ago

2.1.0

10 years ago

2.0.0

10 years ago