0

I have an object in JavaScript and I would like to find the one value that is an odd number, then return that value's corresponding key. For example:

const myObject = {
                   'a': 4,
                   'b': 6,
                   'c': 7,
                   'd': 8
                  }

From this, I would like to return 'c'. The following is what I have attempted, but I get an error.

const myObject = {
  'a': 4,
  'b': 6,
  'c': 7,
  'd': 8
}
myObject.forEach((i) => {
  if (counts.value[i] % 2 === 0)
    return counts.key[i];
});
j08691
  • 204,283
  • 31
  • 260
  • 272
  • https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays. I believe this question will help you solve your problem – Meher Chaitanya Sep 28 '22 at 17:44

5 Answers5

2

You can use Object.keys to get the array of myObject keys and use find to get the value that is odd.

const myObject = {
   'a': 4,
   'b': 6,
   'c': 7,
   'd': 8
}

let key = Object.keys(myObject).find((key) => myObject[key] % 2)

console.log(key)
Mina
  • 14,386
  • 3
  • 13
  • 26
2

You can use Array#find on Object.keys.

const myObject = {
  'a': 4,
  'b': 6,
  'c': 7,
  'd': 8
};
const res = Object.keys(myObject).find(k => myObject[k] % 2 !== 0);
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

Get object values to array and filter the odd values from the values array

const myObject = { 'a': 4, 'b': 6, 'c': 7, 'd': 8};
const valuesArr = Object.values(myObject);
const result = valuesArr.filter((value) =>  {
   if ((value % 2) !== 0) {
      return value;
   }
});
console.log(result);
John Mack
  • 73
  • 5
2

Find the result in single iteration and return the odd value key.

const myObject = { 'a': 4, 'b': 6, 'c': 7, 'd': 8};
let result = '';

for(const key in myObject) {
  if((myObject[key] % 2) !== 0) {
      result = key;
      break;
  }
}

console.log(result);
//return result;
sasi66
  • 437
  • 2
  • 7
0
  const myObject = {
                       'a': 4,
                       'b': 6,
                       'c': 7,
                       'd': 8
                      };
    Object.keys(myObject).filter((each) => {
    if( myObject[each] % 2 === 1){ 
    return each;
    }
        );