0

I want to parse a string to an object object selector like so :

var test = 'object.prop1.prop2';

into 

object['prop1']['prop2'];

The problem is i don't know how many properties the string could have.

What is the best way to to parse a string accross, idealy without something like json parse/ eval?

frank astin
  • 23
  • 1
  • 8

2 Answers2

1

There is a package for that : https://www.npmjs.com/package/object-path

Alexandre
  • 1,940
  • 1
  • 14
  • 21
0

Juhana's link is excellent, but also a bit more of a complex problem than the one you have here. Here is my take (https://jsfiddle.net/gm32f6fp/3/):

var object = {
    prop1: {
        prop2: {
            foo: 1
        }
    }
};

function get(object, key) {
    var keys = key.split('.');
    for (var i = 0; i < keys.length; i++) {
        if (!object.hasOwnProperty(keys[i])) {
            return null;
        }
        object = object[keys[i]];
    }
    return object;
}

console.log(get(object, 'prop1.prop2'));
console.log(get(object, 'prop1.prop3'));

The idea is to take the string of keys, split it based on the dot. Then you have an arbitrarily large array of keys, so we take each key, one by one, and dive into the object. (If we end up at a dead end, we bail out.)

Matthew King
  • 1,342
  • 7
  • 13