just.parent(objectnon-null, pathopt, handleropt, opts) → {*}
Accesses to a deep property in a new object (or object if mutate evals to `true`).
Parameters:
Name | Type | Default | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
object | object | The base object. | |||||||||||||
path [optional] | string[] | [path] | The ordered keys. | ||||||||||||
handler [optional] | just.access~handler | returnValue | A custom function. | ||||||||||||
opts | object | Properties
|
Throws:
If some property causes access problems.
- Type
- TypeError
Returns:
If handler is given: the returned value of that function, otherwise: the last value of path in the copied object.
- Type
- Any
Examples
just.access({a: {b: {c: {d: 4}}}}, ['a', 'b', 'c', 'd'], function (currentObject, currentKey, hasProperty, path) {
return hasProperty ? currentObject[currentKey] : null;
}); // returns 4.
just.access({a: 1}, ['a', 'b', 'c']); // throws TypeError.
just.access({a: 1}, ['a', 'b', 'c'], null, {
'override': true
}); // returns undefined.
// Doesn't throw because it replaces `1` with an empty object
// and keeps accessing to the next properties.
var obj = {z: 1, prototype: [...]};
var newObj = just.access(obj, 'a.b.c'.split('.'), function (currentObject, currentKey, hasProperty, path) {
if (!hasProperty) {
currentObject[currentKey] = path.length;
}
// At this point:
// `obj` is {z: 1},
// `currentObject` has a value in `currentKey`,
// and `this` has all the added keys (even the ones modified in `currentObject`).
return this;
}); // returns {z: 1, a: {b: {c: 3}}}
// if you want the prototype chain of obj, just copy it.
just.assign(newObj.prototype, obj.prototype);
var obj = {a: {b: false}, b: {b: false}, prototype: [...]};
just.access(obj, 'a.b'.split('.'), function (currentObject, currentKey, hasProperty, path) {
currentObject[currentKey] = 2;
}, true);
// now `obj` is {a: {a: true}, b: {b: true}, prototype: [...]}.