getobject.js
1.5 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* getobject
* https://github.com/cowboy/node-getobject
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
*/
'use strict';
var getobject = module.exports = {};
// Split strings on dot, but only if dot isn't preceded by a backslash. Since
// JavaScript doesn't support lookbehinds, use a placeholder for "\.", split
// on dot, then replace the placeholder character with a dot.
function getParts(str) {
return str.replace(/\\\./g, '\uffff').split('.').map(function(s) {
return s.replace(/\uffff/g, '.');
});
}
// Get the value of a deeply-nested property exist in an object.
getobject.get = function(obj, parts, create) {
if (typeof parts === 'string') {
parts = getParts(parts);
}
var part;
while (typeof obj === 'object' && obj && parts.length) {
part = parts.shift();
if (!(part in obj) && create) {
obj[part] = {};
}
obj = obj[part];
}
return obj;
};
// Set a deeply-nested property in an object, creating intermediary objects
// as we go.
getobject.set = function(obj, parts, value) {
parts = getParts(parts);
var prop = parts.pop();
obj = getobject.get(obj, parts, true);
if (obj && typeof obj === 'object') {
return (obj[prop] = value);
}
};
// Does a deeply-nested property exist in an object?
getobject.exists = function(obj, parts) {
parts = getParts(parts);
var prop = parts.pop();
obj = getobject.get(obj, parts);
return typeof obj === 'object' && obj && prop in obj;
};