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