This repository has been archived by the owner on Oct 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (58 loc) · 1.41 KB
/
index.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
'use strict';
/*!
* dot2val
* Set or get a value within a deeply nested object using `dot' notation
* @author Brook Yang https://github.com/yangg/dot2val
*/
var dot2val = {
/**
* sets a value within a deeply nested object using "dot" notation
*/
set: function(obj, parts, val) {
if(!Array.isArray(parts)) {
parts = parts.split('.');
}
var k = parts[0];
if(parts.length > 1) {
var partsLength = parts.length
k = parts[partsLength - 1];
for(var i = 0; i < partsLength - 1; i++) {
var part = parts[i]
if(! obj.hasOwnProperty(part)) {
obj[part] = {};
}
obj = obj[part];
}
}
if(typeof val !== 'undefined') {
obj[k] = val;
} else {
delete obj[k];
}
},
/**
* retrieves a value from a deeply nested object using "dot" notation
*/
get: function(obj, parts, def) {
if(!Array.isArray(parts)) {
parts = parts.split('.');
}
var k = parts[0];
if(parts.length > 1) {
var partsLength = parts.length
k = parts[partsLength - 1];
for(var i = 0; i < partsLength - 1; i++) {
var part = parts[i]
if(! obj.hasOwnProperty(part)) {
obj = false;
break
}
obj = obj[part];
}
}
return obj ? (typeof obj[k] !== 'undefined' ? obj[k] : def) : def;
}
};
if(typeof module !== 'undefined') {
module.exports = dot2val;
}