1

How can I get the method getValueThroughPath(object, keysArray) that works like so:

var object = {
  key1: {
    key2: {
      key3: {
        key4: "value"
      }  
    }
  }
}

getValueThroughPath(object, ['key1', 'key2', 'key3', 'key4']); // = "value" and undefined if wrong path

?

I'm also looking for the setValueThroughPath(object, keysArray) equivalent method.

I use Lodash if this can shorten the solution.

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

2 Answers2

2

This will walk the object down to the last key. If any key is misspelled or missing, it will return undefined:

function getValueThroughPath(obj, keys) {
  while(obj=obj[keys.shift()] || '', keys.length);
  return obj || undefined;
}

function setValueThroughPath(obj, keys, val) {
  while(keys.length>1) {
    obj[keys[0]]= obj[keys[0]] || {};
    obj= obj[keys.shift()];
  };
  obj[keys[0]]= val;
}

var object = {
  key1: {
    key2: {
      key3: {
        key4: "value"
      }  
    }
  }
}

setValueThroughPath(object, ['this', 'is', 'a', 'test'], 'Eureka!');
setValueThroughPath(object, ['this', 'is', 'a', 'new', 'test'], 'Hallelujah!');

console.log(getValueThroughPath(object, ['key1', 'key2', 'key3', 'key4']));   // "value"
console.log(getValueThroughPath(object, ['key1', 'key2', 'key5', 'key4']));   // undefined
console.log(getValueThroughPath(object, ['this', 'is', 'a', 'test']));        // "Eureka!"
console.log(getValueThroughPath(object, ['this', 'is', 'a', 'new', 'test'])); // "Hallelujah!"
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
0

You can iterate through your object properties and get the appropriate value using a function like this:

function getValueThroughPath(object, keys) {
    var temp = object;
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (temp.hasOwnProperty(key)) {
            temp = temp[key];
            console.log(JSON.stringify(temp));
        } else {
            console.log('Couldnt find key ' + key);
            return undefined;
        }
    }

    return temp;
}

You can check the fiddle at http://jsfiddle.net/bx82akj5/ to see it working (open console to check it out! =D)

I used the "hasOwnProperty" method so you don't end up accessing an inexistent property or accessing a property of Object in javascript, so you iterate only through the properties defined in your object.

The function setValueTrhoughPath that you are looking for is pretty much the same (just analogous, of course)

Gabriel Pires
  • 376
  • 5
  • 9