SDDave
SDDave

Reputation: 23

JS use a single string as key for multidimensional array

Let's say I have this variable:

var myvar = {
    welcome: "Welcome!",
    thx: "Thank you!",
    ...
}

Then, I have a function, which gets sent a string and return the value from that variable:

function myFunction(key){
    return myvar[key]
}

So this happens:

console.log(myFunction('welcome')) ///prints Welcome!

That's all great, and works beautifully, but what if then I wanna add something like months to the original variable, and I want something like this

var myvar={
    .
    .
    months: [
        ["jan", "January"],
        ..
}

So if I wanna call for example, January, I'd do

myvar[months][0][1] //Select the months part, 0 means it's january, 1 means its fully written not just "jan"

I could, for example, in my key do something like months-0-1 and split it to get all 3 keys; but how could I adapt my original function to work for both the original content (welcome, thx) and for the months?

Second part to this question, should I even do it or would it be a not very optimal solution, should I just go with the whole adding each entry into the variable like before method? Note: I still want the answer to my first question, if nothing else because I want to know how it could be done, even if I don't end up doing it.

A bit more information of the use case, I have a data-translate tag on some objects in my html, and some that are generated dynamically, these variables are for language translation, and they all call that function either when they are made or when the language changes. (data-translate="welcome") for example

Upvotes: 1

Views: 120

Answers (2)

namar sood
namar sood

Reputation: 1590

We can do something like this

var myvar = {
    welcome: "Welcome!",
    thx: "Thank you!",
    months: [
        ["jan", "January"]]
};


function myFunction(key){
    let keys = key.split("-");
    let len = keys.length;
    let result = myvar, i=0;
    while(i < len)
        result = result[keys[i++]];
 
    return result;
};

console.log(myFunction("welcome"), myFunction("months-0-0"))

Upvotes: 0

Karan
Karan

Reputation: 12629

You can update your function code to be like below and pass keys as - separated values as you have mentioned. Refer this article Array.prototype.reduce() if you are not familiar with it.

return key.split('-').reduce((a, i) => a[i], myvar);

Try it below.

var myvar = {
  welcome: "Welcome!",
  thx: "Thank you!",
  months: [
    ["jan", "January"]
  ]
};

function myFunction(key) {
  return key.split('-').reduce((a, i) => a[i], myvar);
}

console.log(myFunction('welcome')); // prints Welcome!
console.log(myFunction('months-0-1')); // prints January!

Upvotes: 3

Related Questions