简体   繁体   中英

assign variable to value of Dictionary Javascript

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

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.

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)

I must apologise as when I asked the question I wasn't fully clear on what I needed but after some experimentation and looking at my edge cases and after looking at Krzysztof's answer I had a thought and came up with something similar to this -


const dict = {
 key: (eventData) => {
          return [
            {
              module: 'company',
              entity: 'placement',
              variables: {
                placement_id: {
                  value: eventData.id,
                },
              },
            },
            {
              module: 'company',
              entity: 'placement',
              variables: {
                client_id: {
                  value: eventData.client.id,
                },
              },
            },
          ];
        },
      }

Then I'm getting the data like this -

const data = dict?.[key](eventData)

console.log(data)

I can then navigate or manipulate the data however I need.

thank you everyone who spent time to help me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM