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

时间:2016-04-06 01:15:30

标签: javascript json node.js node.js-stream node.js-client

这是我的目标:

    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是从db表中提取的,并不是特定的。

1 个答案:

答案 0 :(得分:1)

您可以将hibernate_sequence分割为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;