1

I've got a recursive function to go through an object and take what is needed using path string like jsonObj.object.item.value. The idea is to upgrade it somehow to support arrays.

const getValue = function(pathVar, obj) {
  obj = obj || x;
  // get very first node and the rest
  let [node, restNodes] = pathVar.split(/\.(.+)/, 2)
  // get interim object
  ret = obj[node];
  if(ret === undefined) return undefined;
  // pass rest of the nodes further with interim object
  if(restNodes) return getValue(restNodes, ret);
  return ret;
};

Right now on each iteration simple regexp splits path string like jsonObj.object.item.value into jsonObj and object.item.value

the idea is to add array support here, so I can do transformations like

car.engine.something => car and engine.something
wheels[2].material.name => wheels and [2].material.name
[2].material.name => 2 and material.name
car.wheels[4] => car and wheels[4]

Any ideas how to do it?

1
  • why do you want to re-invent the wheel? there is _.get method that does exactly that, lodash.com/docs/4.17.11#get Commented May 29, 2019 at 15:11

1 Answer 1

1

You could use eval which will just evaluate the expression. As for a functional approach, use the following.

function getValue(path, obj) {
    obj = obj || self; // self is the global window variable
    if( !path )
        return obj;

    let pattern = /(?:\["?)?(\w+)(?:\.|"?])?(.*)/i;

    let [ full, property, rest ] = path.match(pattern);
    return getValue( rest, obj[ property ] );
}

self.obj = { foo: [ 2, {bar: "baz"} ] };
console.log(getValue('obj.foo[1]["bar"]')) // 'baz'

Pattern uses four groups. The first is non-capturing and expects a possible ["this will help match array or object properties. Then we expect a series of alphanumerics which we capture. Then another non capturing group to either close "] or match a .. Finally we capture the rest to use in the next call.

Again eval is capable of all of this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.