Home > Back-end >  Can't get key from value within an object
Can't get key from value within an object

Time:09-01

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
    };

CodePudding user response:

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 }

CodePudding user response:

You can use like that;

const newCountryList = {
        [employeeCountryName]: employeeCountryCode
    };

By the way, in your case find function couldn't find any key-value pair so it returns undefined. Because "United Kingdom" field has a GBR value and you're trying to find GBP

  • Related