Search code examples
javascriptarraysloopsobjectarray-map

how to get the object key if the object and array value matches in javascript


I would like to know how to compare object value and array value in javascript

if the array value and object value is same, then how to return the

object key value in javascript


var result = obj.values(obj).includes(arr2) ? 
'status: active' : 'status: inactive'

var obj = {
  "active": 12,
  "inactive": 14
  "neutral": 16
}

var arr1=[12]
var arr2=[12, 14]
var arr3=[12, 16]

Expected Output

//for arr1
status: active
// for arr2
status: active
status: neutral
// for arr3
status: active
status: inactive


Solution

  • You can simply iterate through the array, and then attempt to fetch the [key, value] tuples returned by Object.entries(obj) whose value matches the array value. Once found, you return the key in the tuple, i.e.:

    arr.map(v => Object.entries(obj).find(x => x[1] === v)[0]);
    

    Note: If you array may contain values that are not present in the object, the code above will throw an error because .find() will return undefined. If that's the case, you need to catch cases where an invalid value is used (defensive design):

    arr.map(v => {
      const foundTuple = Object.entries(obj).find(x => x[1] === v);
      return foundTuple ? foundTuple[0] : null;
    });
    

    See proof-of-concept below:

    const obj = {
      "active": 12,
      "inactive": 14,
      "neutral": 16
    }
    
    const arr1 = [12];
    const arr2 = [12, 14];
    const arr3 = [12, 16];
    const invalid_arr = [12, 999];
    
    function getKeys(obj, arr) {
      return arr.map(v => {
        const foundTuple = Object.entries(obj).find(x => x[1] === v);
        return foundTuple ? foundTuple[0] : null;
      });
    }
    
    console.log(getKeys(obj, arr1));
    console.log(getKeys(obj, arr2));
    console.log(getKeys(obj, arr3));
    console.log(getKeys(obj, invalid_arr));