skip to Main Content

I have a object as given below:

const obj = {
        "[email protected]": "email one",
        "[email protected]": "email two",
}

How to get object key if their value matched with given variable:

var outputVal = "email two"; 
    Object.entries(obj ).map(([key,value])=>{
          if(outputVal === value){
            console.log('output', key);
}

3

Answers


  1. Working fine

    const obj = {
      "[email protected]": "email one",
      "[email protected]": "email two",
    }
    
    var outputVal = "email two";
    
    Object.entries(obj).forEach(([key, value]) => {
      if (outputVal === value) {
        console.log('output', key);
      }
    })

    You can use find on object

    const obj = {
      "[email protected]": "email one",
      "[email protected]": "email two",
    };
    var outputVal = "email two";
    const key = Object.values(obj).find((key) => outputVal === key);
    console.log(key);
    Login or Signup to reply.
  2. Use find() on Object.keys(obj)

    const obj = {
            "[email protected]": "email one",
            "[email protected]": "email two",
    }
    
    const value = "email two";
    
    const keyMatch = Object.keys(obj).find(k => obj[k] === value);
    console.log(keyMatch);
    Login or Signup to reply.
  3. Your problem can be simplified by swapping the keys/values around. Just interrogate the object key to get its value.

    const obj = {
      "email one": "[email protected]",
      "email two": "[email protected]"
    }
    
    const query = "email two";
    console.log(obj[query]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search