-
-
Save evert0n/2c661574c0844b699077 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getObj = { | |
a: { | |
foo: 1, | |
bar: 2 | |
} | |
}; | |
var objectPath = function(obj, path, value, options){ | |
path = typeof path == 'string' ? path.split('.') : path; | |
var key = path.shift() | |
, result = {}; | |
if(key && path.length){ | |
if(!obj[key]){ | |
if(value) | |
obj[key] = {}; | |
else | |
return undefined; | |
} | |
if(!value) | |
return objectPath(obj[key], path, value, options); | |
else | |
obj[key] = objectPath(obj[key], path, value, options); | |
} else { | |
if(value){ | |
typeof obj == 'object' || (obj = {}); | |
result[key] = obj[key] = value; | |
return obj; | |
} else { | |
if(options && options.unset){ | |
delete obj[key]; | |
} else { | |
return obj[key]; | |
} | |
} | |
} | |
} | |
var has = function(obj, path){ | |
path = typeof path == 'string' ? path.split('.') : path; | |
if(!obj || 'object' !== typeof obj) | |
return false; | |
var currentKey = path.shift(); | |
if(currentKey){ | |
if(!path.length){ | |
return obj.hasOwnProperty(currentKey); | |
} | |
return has(obj[currentKey], path); | |
} | |
} | |
//objectPath(getObj, 'a', 55); | |
console.log('Original object', getObj); | |
objectPath(getObj, 'a.b', 66); | |
console.log('Object after set', getObj); | |
console.log('get a.b>', objectPath(getObj, 'a.b')); | |
//unset | |
objectPath(getObj, 'a.b', undefined, { unset: 1 }); | |
console.log('unset a.b>', getObj); | |
//has | |
console.log('getObj has a?>', has(getObj, 'a')); | |
console.log('getObj has a.foo?>', has(getObj, 'a.foo')); | |
console.log('getObj has a.foo.faz?>', has(getObj, 'a.foo.faz')); | |
console.log('getObj has a.baz?>', has(getObj, 'a.baz')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment