|
1
|
|
|
export default { |
|
2
|
|
|
/** |
|
3
|
|
|
* Get element from obj by string path |
|
4
|
|
|
* Example: |
|
5
|
|
|
* Given the object let a = {a: {b: 1}} |
|
6
|
|
|
* When you do getFlattened("a.b", a) |
|
7
|
|
|
* Then you get the number 1. |
|
8
|
|
|
* @param {string} path specify the key of the object you want |
|
9
|
|
|
* @param {Object} obj reference object |
|
10
|
|
|
* @param {any} defaultValue value to return if key was not found. Default is null |
|
11
|
|
|
* @return {any} |
|
12
|
|
|
*/ |
|
13
|
|
|
getFlattened: function (path, obj, defaultValue = null) { |
|
14
|
4 |
|
if (typeof path !== "string") { |
|
15
|
|
|
throw "path must be string"; |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
let i; |
|
19
|
4 |
|
let response = obj; |
|
20
|
4 |
|
const explodedPath = path.split("."); |
|
21
|
4 |
|
const size = explodedPath.length; |
|
22
|
|
|
|
|
23
|
4 |
|
for (i = 0; i < size; i++) { |
|
24
|
11 |
|
if (response instanceof Object === false) { |
|
25
|
|
|
return defaultValue; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
11 |
|
if (response.hasOwnProperty(explodedPath[i])) { |
|
29
|
10 |
|
response = response[explodedPath[i]]; |
|
30
|
|
|
} else { |
|
31
|
1 |
|
return defaultValue; |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
3 |
|
return response; |
|
36
|
|
|
}, |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @see getFlattened |
|
40
|
|
|
* Similar to getFlattened, but it set the value instead of return it. |
|
41
|
|
|
* Example: |
|
42
|
|
|
* Given the object let b = {a: {b: 1}} |
|
43
|
|
|
* When you do setFlattened("a.b", 2) |
|
44
|
|
|
* Then you get {a: {b: 2}} |
|
45
|
|
|
* @param {String} path |
|
46
|
|
|
* @param {*} newValue |
|
47
|
|
|
* @param {Object} obj |
|
48
|
|
|
* @returns {*} |
|
49
|
|
|
*/ |
|
50
|
|
|
setFlattened: function (path, newValue, obj) { |
|
51
|
|
|
"use strict"; |
|
52
|
|
|
|
|
53
|
2 |
|
const explodedPath = path.split("."); |
|
54
|
2 |
|
const laps = explodedPath.length - 1; |
|
55
|
|
|
let i; |
|
56
|
2 |
|
let temp = obj; |
|
57
|
|
|
|
|
58
|
2 |
|
for (i = 0; i < laps; i += 1) { |
|
59
|
2 |
|
temp = temp[explodedPath[i]]; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
2 |
|
temp[explodedPath[laps]] = newValue; |
|
63
|
2 |
|
return obj; |
|
64
|
|
|
}, |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Get first key of an object or null if it doesn't have keys |
|
68
|
|
|
* @param {Object} obj |
|
69
|
|
|
* @returns {*} |
|
70
|
|
|
*/ |
|
71
|
|
|
firstKey: function (obj) { |
|
72
|
|
|
"use strict"; |
|
73
|
|
|
|
|
74
|
2 |
|
if (obj instanceof Object === false) { |
|
75
|
|
|
throw "obj must be an Object"; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
2 |
|
return Object.keys(obj)[0] || null; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|