There is a function that returns a value for the key I specified.
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
But want to using like this, how can i do that.
l('sidebar.a') // Now its undifined
You need to dig in recursively, here's one possible solution (also a recursive function, although that's not necessary):
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"));