-
Notifications
You must be signed in to change notification settings - Fork 0
/
dot-path.js
74 lines (67 loc) · 1.95 KB
/
dot-path.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var _ = require('underscore');
var ObjectPath = {};
/**
* Return the value of a nested object property from it path.
*
* Usages:
* - ObjectPath.getPath(document.body, 'style.width')
* - ObjectPath.getPath(someObject, 'part3.0.size')
* - ObjectPath.getPath({}, 'properties.that.do.not.exist') === undefined
*
* @param obj {Object} An object
* @param path {String} The path of the nested property to get.
* @return {*} The value of the nested property or undefined if the property doesn't exist.
*/
ObjectPath.getPath = function (obj, path) {
return path.split('.').reduce(function (prev, curr) {
return prev ? prev[curr] : undefined;
}, obj);
};
/**
* Set the value of a nested object property.
*
* Usages:
* - ObjectPath.setPath({}, 'a.nested.prop', 'myValue') === { a: { nested: { prop: 'myValue' } } }
*
* @param obj {Object}
* @param path {String}
* @param value {*}
* @param options {Object}
* @returns {Object} The object passed as input parameter set with the nested property.
*/
ObjectPath.setPath = function (obj, path, value, options = {}) {
options = _.extend({
deleteEmptyString: false,
nullEmptyString: false,
undefinedEmptyString: false,
}, options);
path = (typeof path === 'string') ? path.split('.') : path;
const firstSegment = path.shift();
if (path.length === 0) {
// Stop condition
if (value === '') {
if (options.deleteEmptyString) {
delete obj[firstSegment];
} else if (options.nullEmptyString) {
obj[firstSegment] = null;
} else if (options.undefinedEmptyString) {
obj[firstSegment] = undefined;
}
} else {
obj[firstSegment] = value;
}
} else {
// Progress condition
obj[firstSegment] = ObjectPath.setPath(
(typeof obj[firstSegment] === 'object' ? obj[firstSegment] : {}),
path,
value,
options,
);
}
return obj;
};
module.exports = {
getPath: ObjectPath.getPath,
setPath: ObjectPath.setPath,
};