Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get key from value within an object

I am trying to get the value associated with a key and create a new object, such as below. However when I assign the value of employeeCountryName to the object newCountryList, i get employeeCountryName returned and not "United Kingdom".

Any thoughts why this may be?

   const countryList = {
        "United Kingdom": "GBR"
    };

    const employeeCountryCode = "GBP"

    const getKey = (obj, val) => Object.keys(obj).find(key => obj[key] === val);

    const employeeCountryName = getKey(countryList, employeeCountryCode);

    const newCountryList = {
        employeeCountryName: employeeCountryCode
    };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Keep in mind that when you define an object, it’s keys aren’t based on any other variables by default, they are just strings taken as keys. In order to tell javascript to take the value of a variable you have predefined instead of using it directly as a key, you need to add [] around them like this:

const variableName = 'keyToUse';
const object = { [variableName]: 1 } // { keyToUse: 1 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading