[英]Getting object in object value
有一个函数可以为我指定的键返回一个值。
function l(key){
let selectedLang = window.localStorage.getItem('language') || lang.default;
return lang[selectedLang][key];
}
const en = {
sidebar : {
"a" : "b",
}
}
l('sidebar') // function gives an object, its okey
但是想像这样使用,我该怎么做。
l('sidebar.a') // Now its undifined
您需要递归地挖掘,这是一个可能的解决方案(也是一个递归函数,尽管这不是必需的):
const obj = {foo: "Foo", bar: {baz: "Bar Baz"}} const access = (object, path) => { const pathArray = Array.isArray(path) ? path : path.split("."); const lastIndex = pathArray.length - 1; return lastIndex > 0 ? access(object, pathArray.slice(0, lastIndex))[pathArray[lastIndex]] : object[pathArray[0]]; } console.log(access(obj, ["foo"])); console.log(access(obj, ["bar", "baz"])); console.log(access(obj, "bar.baz"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.