给出以下obj:
var inputMapping = {
nonNestedItem: "someItem here",
sections: {
general: "Some general section information"
}
};
Run Code Online (Sandbox Code Playgroud)
我正在get通过传入字符串"nonNestedItem"或嵌套的情况为该数据编写函数"sections.general".我不得不使用一个eval,我想知道是否有更好的方法来做到这一点.
这是我到目前为止所做的,它可以正常工作.但改善!
function getNode(name) {
var n = name.split(".");
if (n.length === 1) {
n = name[0];
} else {
var isValid = true,
evalStr = 'inputMapping';
for (var i=0;i<n.length;i++) {
evalStr += '["'+ n[i] +'"]';
if (eval(evalStr) === undefined) {
isValid = false;
break;
}
}
if (isValid) {
// Do something like return the value
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的Array.prototype.reduce功能
var accessString = "sections.general";
console.log(accessString.split(".").reduce(function(previous, current) {
return previous[current];
}, inputMapping));
Run Code Online (Sandbox Code Playgroud)
产量
Some general section information
Run Code Online (Sandbox Code Playgroud)
如果您的环境不支持reduce,则可以使用此递归版本
function getNestedItem(currentObject, listOfKeys) {
if (listOfKeys.length === 0 || !currentObject) {
return currentObject;
}
return getNestedItem(currentObject[listOfKeys[0]], listOfKeys.slice(1));
}
console.log(getNestedItem(inputMapping, "sections.general".split(".")));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |