1

Path variable is unpredictable. Sometimes it is just a, sometimes a/b, sometimes a/b/c etc. I want to reach a node dynamically according to path. The code below behaves what i want but i can consider if there is a better way to do that without eval for example.

http://jsfiddle.net/nuonzngv/1/

cont = {
    "a" : {
        "b": {
            "c": "d"
        }   
    }
}
path = "a/b/c";
sect = path.split("/");

path = "cont";
$.each(sect, function( index, value ) {
    path = path + "['" + value + "']";
});

console.log(eval(path));

Solution

I found a plugin that has a getPath function in it, for underscore.js: https://github.com/documentcloud/underscore-contrib/blob/master/docs/underscore.object.selectors.js.md

fozuse
  • 754
  • 2
  • 11
  • 29
  • Why don't you access `cont` directly in the loop? – sebnukem Nov 19 '14 at 23:23
  • 1
    It may be simpler to convert your current structure to a single object with many properties aka flatten, this could be done dynamically. Refer to http://stackoverflow.com/questions/19436457/how-flatten-object-literal-properties If you needed a/b/c to convert to abc you can modify the answer to include each level's parent property name. – AIDA Nov 19 '14 at 23:30
  • Path is coming from URL – fozuse Nov 19 '14 at 23:32
  • 1
    See this post about finding nested objects by key: http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key. Lots of ways to solve the problem. – Robert Munn Nov 20 '14 at 00:00
  • Looks lodash have a getPath function that do the job. That would be great if underscore.js have similar function? I really dont want to include another library to my project ); – fozuse Nov 20 '14 at 00:52

2 Answers2

2

Can you access your cont object directly in the loop? If so:

var cont = {
    "a" : {
      "b": {
        "c": "d"
      }   
    }
  },
  o = cont,
  path = "a/b/c",
  sect = path.split("/");

path = "cont";
$.each(sect, function(index, value) {
  path = path + "['" + value + "']";
  if (o) o = o[value];
});

console.log(path+'='+o);

gives:

cont['a']['b']['c']=d

An invalid path will return undefined.


*Edit: psibernetic's comment suggesting creating a standalone function:

function GetByPath(obj, path) {
  var result = obj;
  $.each(path.split("/"), function(index, value) {
    if (typeof result !== 'undefined' && result !== null) {
      result = obj[value];
    }
  }
  return result;
}
sebnukem
  • 8,143
  • 6
  • 38
  • 48
  • function GetByPath(cont, path) { var result = cont; $.each(path.split("/"), function(index, value) { if(typeof result !=== 'undefined' && result !== null) { result = cont[value]; } } return result; } – AIDA Nov 20 '14 at 00:05
1
function GetByPath(cont, path)
{
     var result = cont;
     $.each(path.split("/"), function(index, value) {
        if(typeof result !== 'undefined' && result !== null) {
            result = cont[value];
        }
     }
     return result;
}
AIDA
  • 519
  • 2
  • 14