【问题标题】:Node.js: variable to act as nested element name for an object [duplicate]Node.js:充当对象嵌套元素名称的变量[重复]
【发布时间】:2016-07-26 04:27:00
【问题描述】:
这是我的对象:
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 表中提取的,并不具体。
【问题讨论】:
标签:
javascript
json
node.js
node.js-stream
node.js-client
【解决方案1】:
您可以将 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' />