Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Extract nested property from object. If nested property cannot be reached, return value of rescue
- * @param obj Object
- * @param path Can be dot-separated string or array
- * @param rescue (optional) default value. Defaults to null
- */
- function extract(obj, path, rescue){
- if (typeof obj === "object" && path){
- var elements = typeof path === "string" ? path.split(".") : path;
- if (typeof elements.shift === "function"){
- var head = elements.shift();
- if (obj.hasOwnProperty(head)){
- return (elements.length === 0) ? obj[head] : extract(obj[head], elements, rescue);
- } // if
- } // if
- } // if
- return rescue || null;
- } // extract
- var noob = {k1 : {k11 : {k111 : "v1"}}, k2 : { k21 : "v2"}};
- console.log(extract(noob, 'k1.k11')); // {k111 : "v1"}
- console.log(extract(noob, 'k1.k11.k111')); // v1
- console.log(extract(noob, ['k1', 'k11', 'k111'])); // v1
- console.log(extract(noob, 'k1.k11.kx')); // null
- console.log(extract(noob, 'k2')); // k2 : { k21 : "v2"}
- console.log(extract(noob, 'k2.k21.k22')); // null
- console.log(extract(noob, 'k1.k11.k22', "ZUT")); // ZUT
- console.log(extract(noob, '', "ZUT")); // ZUT
- console.log(extract(false, '', "ZUT")); // ZUT
- var x = {
- blah: {
- blam: "bloo"
- }
- }
- with(x) {
- console.log(blah)
- }
- with(x){
- console.log(blah.blam)
- }
- var extract = function(obj, path, rescue){
- with(obj) {
- return eval(path) || rescue;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement