Search code examples
javascriptjsonnode.jsnode.js-streamnode.js-client

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


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.


Solution

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