简体   繁体   中英

Object.entities filter

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

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];
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM