Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a JSON path in array in Javascript? [duplicate]

I have this JSON

var myJSON = {
    "a": {
        "b": {
            "c": {
                "Foo": "Bar"
            }
        }
    }
}

I also have this array:

var path = ["a", "b", "c", "foo"]

How can I use the path to get Bar?

like image 564
Bob van Luijt Avatar asked Sep 03 '15 19:09

Bob van Luijt


2 Answers

Check out Array.prototype.reduce(). This will start at myJSON and walk down through each nested property name defined in path.

var myJSON = {
  "a": {
    "b": {
      "c": {
        "Foo": "Bar"
      }
    }
  }
};

var path = ["a", "b", "c", "Foo"]; // capitalized Foo for you...

var val = path.reduce((o, n) => o[n], myJSON);

console.log("val: %o", val);
like image 158
canon Avatar answered Sep 28 '22 16:09

canon


Have a variable that stores the value of the object, then iterate through the path accessing the next property in that variable until the next property is undefined, at which point the variable holds the end property.

var val = myJSON;

while (path.length) {
    val = val[path.shift()];
}

console.log(val);
like image 45
Elliot Bonneville Avatar answered Sep 28 '22 17:09

Elliot Bonneville