Is there a native way to parse a JavaScript object?

Let's say I want to access a.b.c.d

and I'm not sure if b

or does exist c

. "Naive" check:

if (a.b && a.b.c && a.b.c.d == 5) doSomething(a.b.c.d);

      

I thought about it and wrote this function that improves this:

Object.prototype.parse = function (keys, def) {
  return keys.split('.').reduce(function (prev, curr) {
    if (prev) {
      return prev[curr];
    }
  }, this) || def;

};

      

And you will use it like this:

var a = {
  b: {
    c: {
      d: 5
    }
  }
};

console.log(a.parse('b.c.d', 3)); // If b, c or d are undefined return 3

      

But I'm wondering if I'm missing a better, native way to achieve this instead of adding this feature to projects.

Thank!

+3


source to share


3 answers


The only native way is eval , but I would not recommend it as it can be used to execute arbitrary code. This may be OK, but not if the "abcd" style strings are coming from untrusted users. I would stick with your manual solution or use dotty .

var a = {
  b: {
    c: {
      d: 5
    }
  }
};
console.log(eval("a.b.c.d"));

      



eval () throws the same error as the native equivalent if b or c is not defined, so you will need to wrap a try {} catch {} block.

-2


source


Maybe not exactly what you asked for, but probably as close to "native" as you can get (a slightly more compact version of the snippet / minified snippet):

var a = {b:{c:{d:5}}};
("b.c.d").split(".").reduce(function(p,c){return p && p[c];},a); //5
("b.c.e").split(".").reduce(function(p,c){return p && p[c];},a); //undefined

      



If you were hoping for a type string solution "a.b.c.d"

, then you will need to use eval

(not recoomended), or the object a

should be global (also not recommended), or the object should be a property of another object that is a little overconfident.

+1


source


I think I have another solution to this problem, I have been trying to achieve this for a few minutes. If you are working with a window area, you can use my function to see if an object exists or return the default.

function parseObj(obj){
    try{
        return eval(obj);
    }catch(e){
        return null;
    }
}

      

Using

alert(parseObj("a.b.c.d"));

      


I don't know if this is what you are looking for, but I am sure it will give you another idea. Good job.

-2


source







All Articles