简体   繁体   English

Object.entities 过滤器

[英]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.因此,如果传递的值是 foo,它匹配键 foo 并返回 bar。 I thought object.entities was ideal to use as it has both key & value.我认为 object.entities 非常适合使用,因为它兼具关键和价值。

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.当我使用 for of 语句时 Lint 抱怨并且我返回 undefined 的位置不起作用,因为它退出了条件,但我已经对此进行了注释,并在下面得到关于在箭头 function 中返回值的 lint 错误。

eslint using 'forofstatement' is not alllowed no-restricted-syntax不允许使用 'forofstatement' 的 eslint 无限制语法

Expect to return a value at the end of arrow function consistent return期望在箭头 function 一致返回的末尾返回一个值

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?无法发表评论,因为我还没有足够的代表,但是您是否有理由需要遍历 object 键以找到键值对? 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测试 function 返回键匹配的值,否则返回未定义的值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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