Node.js: variable to act as nested element name for an object

151 Views Asked by At

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.

1

There are 1 best solutions below

0
BrunoLM On BEST ANSWER

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' />