Node.js:用作对象的嵌套元素名称的变量

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

这是我的对象:

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

这是我的 node.js 代码:

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

有什么方法可以实现这个解决方案吗?是因为我的nodeName是从dbtable中提取出来的,不具体。

您可以将 nodeName 拆分为 .,并为每个部分导航对象。

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

console.log(result); // 2012

示例:

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