0

Say I have a JSON object like this:

var a = {
  "b" : {
    "c" : 1
  }
}

is there a quick way to get at c when I know the string "b.c" ?

I guess I could split the string by dots then drill down into c from that but I was hoping there was a quick way to do this in one go.

like I was hoping maybe var c = a["b.c"] but that doesnt work

Trant
  • 3,461
  • 6
  • 35
  • 57

2 Answers2

4

How about something like this, as you suggested using a split:

var a = {
  "b" : {
    "c" : 1
  }
}

var n = "b.c".split(".");
var x = a;
for(var i = 0; i < n.length; i++){
   x = x[n[i]];
}
//x should now equal a.b.c

Here is a working example


In the event that the path is not valid, there is some extra checking that should be done. As my code stands above, x will be undefined if the final part of the path is invalid (e.g "b.d"). If any other part of the path is invalid (e.g. "d.c") then the javascript will error.

Here is a modified example that will end the loop at the first instance of undefined, this will leave x as undefined and will ensure the javascript can continue to execute (no error!)...

var n = "d.c".split(".");
var x = a;
for (var i = 0; i < n.length; i++) {
    x = x[n[i]];
    if (typeof(x) == "undefined") {
        break;
    }
}

Here is an example of this in action

musefan
  • 47,875
  • 21
  • 135
  • 185
1
var a = {
  "b" : {
    "c" : 1
  }
}

var c = "b.c".split(".").reduce(function(obj, key) {
    return obj[key];
}, a);

alert(c)

See reduce. The link also show a how to implement shim for the browsers that doesn't support ES5. Notice that this code is simplified, assumes the keys are present in the objects.

ZER0
  • 24,846
  • 5
  • 51
  • 54