Home > Software engineering >  assign variable to value of Dictionary Javascript
assign variable to value of Dictionary Javascript

Time:12-06

I am building a dictionary but I would like some of the values to contain variables. is there a way to pass a variable to the dictionary so I can assign a dot notation variable? the variables object will always have the same structure and the dictionary will be static and structured the same for each key value pair. essentially I want to pass the value from the dictionary to another function to handle the data.

main.js

import myDictionary from "myDictionary.js"

const variables ={
item:"Hello"
}
const data = myDictionary[key](variables)
console.log(data)


myDictionary.js

const myDictionary = {
key: variables.item
}

so the log should display hello. I know it willl be something straightforward but cant seem to figure it out.

as always any help is greatly appreciated

CodePudding user response:

What you are trying to do is not possible. The myDictionary.js file has no idea whats inside you main file. The only thing you could do would be:

myDictionary.js

const myDictionary = {
    key: "item"
}

main.js

import myDictionary from "myDictionary.js";

const variables = {
    item: "Hello"
};

const data = variables[myDictionary["key"]];
console.log(data);

Also, even though JavaScript does not enforce semi-colons, they will save you a lot of headaches of some stupid rule that breaks the automatic inserter.

CodePudding user response:

You should modify the dictionary so that id does keep callback functions, then it will be able to accept arguments.

const myDictionary = {
  key: (variables) => variables.item
}

const variables = {
  item: "Hello"
}

const key = "key";
const data = myDictionary[key](variables)
console.log(data)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related