1

I have this variable that is stored in a string

  var employee  = {
        name: 'person',
        job: {
           post: 'developer',
           since: 2010,
           desk: {
              number: '1',
        }
    }
  };

How can i get the keychain value from a string e.g.

  var variable = "job.desk.number";
  console.log(variable);
  //this should return 1

UPDATE 3 !!

@T.J. Crowder's answer is actually the best answer.

His function is quick and tidy. :) horry!

4 Answers4

3

Split the string so you have an array of keys, then loop through them getting each key in turn from the object, remembering the last thing you got from the object:

var value = variable.split('.').reduce(function(prev, key) {
  return prev[key];
}, employee);
snippet.log(value);

Example:

var employee  = {
  name: 'person',
  job: {
    post: 'developer',
    since: 2010,
    desk: {
      number: '1',
    }
  }
};

var variable = "job.desk.number";
var value = variable.split('.').reduce(function(prev, key) {
  return prev[key];
}, employee);
snippet.log(value);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Note that Array#reduce is an ES5 thing, so it's in all modern browsers but not some older ones. It can be shimmed/polyfilled, though. Or if you just prefer to use a for loop:

var keys = variable.split('.');
var value = employee;
var index;
for (index = 0; index < keys.length; ++index) {
    value = value[keys[index]];
}
snippet.log(value);

Example:

var employee  = {
  name: 'person',
  job: {
    post: 'developer',
    since: 2010,
    desk: {
      number: '1',
    }
  }
};

var variable = "job.desk.number";
var keys = variable.split('.');
var value = employee;
var index;
for (index = 0; index < keys.length; ++index) {
    value = value[keys[index]];
}
snippet.log(value);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Lets say for example your variable emplyee is like

var employee = "{ name: 'person', job: { post: 'developer', since: 2010, desk: { number: '1', } } }";

which is in fact a string then you need to parse it to JSON using JSON.parse(employee)

And you can access your variable like

var variable = employee.job.desk.number

Alternative to your case is :

var variable = "" + employee.job.desk.number;
0

The result is actually working however i wonder about performance.

 var _getKeyChainValueFromObject = function (keychain, root) {
    var items = [];
    if (keychain.indexOf(".") > 0)
        items = keychain.split(".");
    else
        return root[keychain];

    for (var i = 0; i < items.length ; i++) {
        for (var property in root) {
            var key = items[i];
            if (property === key) {
                if (typeof (root[property]) === "object") {
                    var scope = root[property];
                    items.splice(0, 1);
                    //get the resource recursively 
                    return _getKeyChainValueFromObject(items.join('.'), scope);
                }
            }
        }
    }
};
0

I've found a better solution that works with objects and arrays of objects.

const userObject = {
  user: {
    name: "Victor",
    posts: [
      {
        title: "Post #1",
        description: "........"
      },
      {
        title: "Post #2",
        description: "........"
      }
    ]
  }
};

const path = "user.posts[0].title";

const valueByPath = path.match(/\d+|\w+/gm).reduce(function (prev, key) {
  return prev[key];
}, userObject);

console.log(valueByPath);