3 * https://github.com/cowboy/node-getobject
5 * Copyright (c) 2013 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
11 var getobject = module.exports = {};
13 // Split strings on dot, but only if dot isn't preceded by a backslash. Since
14 // JavaScript doesn't support lookbehinds, use a placeholder for "\.", split
15 // on dot, then replace the placeholder character with a dot.
16 function getParts(str) {
17 return str.replace(/\\\./g, '\uffff').split('.').map(function(s) {
18 return s.replace(/\uffff/g, '.');
22 // Get the value of a deeply-nested property exist in an object.
23 getobject.get = function(obj, parts, create) {
24 if (typeof parts === 'string') {
25 parts = getParts(parts);
29 while (typeof obj === 'object' && obj && parts.length) {
31 if (!(part in obj) && create) {
40 // Set a deeply-nested property in an object, creating intermediary objects
42 getobject.set = function(obj, parts, value) {
43 parts = getParts(parts);
45 var prop = parts.pop();
46 obj = getobject.get(obj, parts, true);
47 if (obj && typeof obj === 'object') {
48 return (obj[prop] = value);
52 // Does a deeply-nested property exist in an object?
53 getobject.exists = function(obj, parts) {
54 parts = getParts(parts);
56 var prop = parts.pop();
57 obj = getobject.get(obj, parts);
59 return typeof obj === 'object' && obj && prop in obj;