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 okay

But I want to use like this, how can I do that?

l('sidebar.a') // Now it's undefined
2
  • 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'] Commented Oct 17, 2021 at 12:44
  • 1
    Does this answer your question? Access property via it's keyPath in Javascript? Commented Oct 17, 2021 at 12:57

1 Answer 1

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"));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.