_.object.builders.js
contains functions that are useful when small changes to JavaScript
objects are needed.
Each section gives use cases showing how a given function could be used:
For some more insights have a look at the tests.
Merges two or more objects starting with the left-most and applying the keys right-word.
Arguments
Returns
(Object): the merged object.
Example
var merged = _.merge({a: 1, b: 1}, {a:2, c: 2}, {a: 3});
merged.a; // → 3
merged.b; // → 1
merged.c; // → 2
Takes an object and another object of strings to strings where the second object describes the key renaming to occur in the first object.
Arguments
obj
that will be used as starting point, it remains unchanged.kobj
string to string mapping defining the renaming.Returns
(Object): obj
with renamed keys.
Example
var obj = {
id: 'tester@test.com',
name: 'tester'
};
var user = _.renameKeys(obj, { 'id': 'email'});
obj.id; // → 'tester@test.com'
user.id; // → undefined
user.email; // → 'tester@test.com'
Snapshots an object deeply. Based on the version by Keith Devens.
Arguments
obj
that will be snapshotted.Returns
(Object): copy of obj
.
Example
var coordsFirstTick = {x: 1, y: 1};
var coordsSecondTick = _.snapshot(coordsFirstTick);
coordsSecondTick.x = 2;
console.log(coordsFirstTick.x); // → 1
Updates the value at any depth in a nested object based on the path described by the keys given. The function provided is supplied the current value and is expected to return a value for use as the new value. If no keys are provided, then the object itself is presented to the given function.
Arguments
obj
that will be updated.fun
that will be applied on the last element of ks
.ks
as a list of steps specifying the path to the attribute that will be updated.defaultValue
that will be used if the key does not exist in obj
.Returns
(Objct): obj
with updated keys.
Example
// we could either give a path to a value in a nested array
var nested = [0, 1, [3, 3], 4];
_.updatePath(nested, _.always(2), [2, 0]); // → [0, 1, [2, 3], 4]
nested; // → [0, 1, [3, 3], 4]
// ...or we could pass an array of keys to traverse
var nested = {
one: {
two: {
three: 4
}
}
};
_.updatePath(nested, _.always(3), ['one', 'two', 'three']).one.two.three; // → 3
nested.one.two.three; // → 4
Sets the value at any depth in a nested object based on the path described by the keys given.
See _.updatePath, this is just syntactic sugar that allows you to pass a value as second parameter, without having to wrap it into a function by yourself.
Returns an object where each element of an array is keyed to the number of times that it occurred in said array.
Arguments
obj
as array or object, as long as the object is not nested the expected object
gets returned.Returns
(Object): with the values as keys and the occurrencies of these as values.
Example
_.frequencies([0, 2, 2, 7, 7, 7]); // → { 0: 1, 2: 2, 7: 3}
_.frequencies({a: 1, b: 1, c: 2, d: 1}) // → {1: 3, 2: 1}