0

Here is my object:

    obj = {
      "FirstName": "Fawad",
      "LastName": "Surosh",
      "Education": {"University": "ABC", "Year": "2012"}
    }

Here is my node.js code:

var nodeName = 'Education.Year';
obj.nodeName; //this should return the value of Year which is '2012'

Is there any way for implementing this solution? It is because my nodeName is extracted from db table and is not specific.

M. Fawad Surosh
  • 450
  • 7
  • 20
  • 2
    See [Accessing nested JavaScript objects with string key](http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) as well as [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Jonathan Lonowski Apr 06 '16 at 01:21

1 Answers1

1

You can split nodeName by . and for each piece navigate the object.

var result;
result = obj['Education'];
result = obj['Year'];

console.log(result); // 2012

Example:

var obj = {
  "FirstName": "Fawad",
  "LastName": "Surosh",
  "Education": {"University": "ABC", "Year": "2012"}
};

var nodeName = 'Education.Year';

var result = nodeName.split('.').reduce((a, b) => {
  a = a[b];
  return a;
}, obj);

document.getElementById('result').value = result;
<input id='result' type='text' />
BrunoLM
  • 97,872
  • 84
  • 296
  • 452