0

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
Şahin Ersever
  • 326
  • 1
  • 8
  • This is because you can only select on level with the `[]`. To dive deeper into an object you need to concatinate multiple `[]`. So in your case `lang['sidebar']['a']` – Jozott Oct 17 '21 at 12:44
  • Does this answer your question? [Access property via it's keyPath in Javascript?](https://stackoverflow.com/questions/17683616/access-property-via-its-keypath-in-javascript) – emptyhua Oct 17 '21 at 12:57

1 Answers1

3

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"));
mbojko
  • 13,503
  • 1
  • 16
  • 26