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
Name
Type
Default
Description
mutate
[optional]
boolean
false
If `true`, it will use
the given object as the base object, otherwise it will
copy all the owned properties to a new object.
override
[optional]
boolean
true
If `true`, and the
current value is different to `null` or `undefined`,
the function will throw a TypeError.
If `false`, the current value will be overriden by
an empty object if it's not an object nor `undefined`.
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
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
|
access({a: {b: {c: {d: 4}}}}, ['a', 'b', 'c', 'd'], function (currentObject, currentKey, hasProperty, path) {
return hasProperty ? currentObject[currentKey] : null;
}); // returns 4.
access({a: 1}, ['a', 'b', 'c']); // throws TypeError.
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 = 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.
Object.assign(newObj.prototype, obj.prototype);
var obj = {a: {b: false}, b: {b: false}, prototype: [...]};
access(obj, 'a.b'.split('.'), function (currentObject, currentKey, hasProperty, path) {
currentObject[currentKey] = 2;
}, true);
// now `obj` is {a: {a: true}, b: {b: true}, prototype: [...]}.