0

I'm getting a big, nested JSON response from an online API. I require only 3 values from it, but they are quite nested. I do know the exact path to each of those fields. For example, given:

obj = {
    "result": {
        "data": {
            "point1": "x",
            "value": 2
        },
        "foo": {
            "bar": 7
        }
    }
}

And the path let p = 'result.data.value' I'd like to be able to do let x = getElement(obj, p); and have x be 2.

I wrote a simple function (removed all the error checking to keep clean):

const getJSONElement = (data, path) => {
  for(let p of path.split('.')) {
    data = data[p];
  }
  return data;
};

It works, but I feel like I'm missing something, or not being efficient. Is there there's a better way to get to the element (perhaps using Array.reduce)?

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • If importing a library is an option, i'd recommend selectn: https://github.com/wilmoore/selectn.js . It will work for your case, but can also handle null checks, array indices, etc. – Nicholas Tower Sep 13 '17 at 18:23
  • Or https://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string or https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key or https://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string or https://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference – user229044 Sep 13 '17 at 18:28
  • Thanks @meagar, I tried searching for similar questions, but I guess I didn't try well enough. At any rate, I got the answer using `reduce` so that's a plus :) – Traveling Tech Guy Sep 13 '17 at 18:37

1 Answers1

3

You could reduce the object with the splitted path values.

var object = { result: { data: { point1: "x", value: 2 }, foo: { bar: 7 } } },
    path = 'result.data.value',
    getValue = (o, p) => p.split('.').reduce((r, k) => r[k], o);

console.log(getValue(object, path));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392