-1
const mykeys = {
  'foo' : 'bar',
  'tez' : 'test',
  'baz' : 'test2'
}

function test(passedValue) {
   //This Arrow function needs to return something else lint complains hence the undefined. Cannot use ForOf lint complains
   Object.entries(mykeys).forEach(([key, val]) => {
   if (key === passedValue) {
     return val
   }
  // return undefined
  })
}

Is there an elegant way to return the value where key matches passed Value. So if passed value is foo it matches key foo and returns bar. I thought object.entities was ideal to use as it has both key & value.

Lint complains when I use for of statement and where I return undefined doesn’t work as that exits the condition, but I’ve commented that out, and get the lint error below about returning a value in the arrow function.

eslint using 'forofstatement' is not alllowed no-restricted-syntax

Expect to return a value at the end of arrow function consistent return

Harry
  • 521
  • 7
  • 21
sam
  • 109
  • 2
  • 3
  • 12
  • `Array.prototype.find()` – Andreas Oct 09 '19 at 16:30
  • Possible duplicate of [How do I check if an object has a key in JavaScript?](https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript) – slider Oct 09 '19 at 17:06

2 Answers2

-1

Can't comment as I don't have enough rep yet, but is there a reason you need to iterate over the object keys to find the key-value pair? Seems to me it'd be easier to instantly look up the value like the following:

function getValue(key){
   return mykeys[key];
}
CoGaMa64
  • 20
  • 2
  • Agree, your answer is also sufficient, some of my keys are duplicated so want to do a filter through the entire list. Dikaeinstein answer has given me a good pointer of what I need to do and where I was going wrong. Do appreciate your answer to. Thanks – sam Oct 09 '19 at 18:16
-1

This is what you want. The other answer was almost there but checking against the value instead of the key. The test function returns the value where key matches or undefined if otherwise

const mykeys = {
  'foo': 'bar',
  'tez': 'test',
  'baz': 'test2'
}

const test = passedValue => 
  (Object.entries(mykeys).find(entry => entry[0] === passedValue) || [])[1];

console.log('test', test('foo'))
console.log('test', test('tez'))
console.log('test', test('baz'))
console.log('test', test('bab'))
Dikaeinstein
  • 26
  • 2
  • 4