-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnestedUtil.js
More file actions
44 lines (38 loc) · 1.36 KB
/
nestedUtil.js
File metadata and controls
44 lines (38 loc) · 1.36 KB
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
function genericSetNestedAttribute(object, path, value, _function) {
let tempObject;
if (!path) throw new Error('Argument path not informed');
if (!object) throw new Error('Argument object not informed');
let splittedPath = path.split('.');
if (splittedPath.length == 1) {
_function(object, path, value);
} else { // > 1
tempObject = object;
for (let index = 0; index < splittedPath.length - 1; index++) {
const nestedObject = splittedPath[index];
if (!tempObject[nestedObject]) tempObject[nestedObject] = {};
tempObject = tempObject[nestedObject];
}
let attribute = splittedPath[splittedPath.length - 1];
_function(tempObject, attribute, value);
}
}
function pushNestedAttribute(object, path, value) {
genericSetNestedAttribute(object, path, value, pushValue);
}
function setNestedAttribute(object, path, value) {
genericSetNestedAttribute(object, path, value, setValue);
}
function setValue(object, attribute, value) {
object[attribute] = value;
}
function pushValue(object, attribute, value) {
if (!object[attribute]) object[attribute] = [];
object[attribute].push(value);
}
module.exports = {
setNestedAttribute: setNestedAttribute,
pushNestedAttribute: pushNestedAttribute,
pushValue,
setValue,
genericSetNestedAttribute
};