简体   繁体   English

"Javascript获取包含值的键索引"

[英]Javascript get Index of Key which contains value

I was wondering if there is a better way to get the Index of Key whose values contain the given value, otherwise it returns Null.我想知道是否有更好的方法来获取其值包含给定值的键索引,否则它返回 Null。 In the example below it does what i need, but wasn't sure not sure if there was a simpler way of writing it.在下面的示例中,它可以满足我的需要,但不确定是否有更简单的编写方式。 I know javascript's syntax is quite powerful and I'm not as familiar with it as others may be.我知道 javascript 的语法非常强大,但我并不像其他人那样熟悉它。

 const sets = { "Set 1": [2, 3], "Set 2": [4, 5], "Set 3": [6] } function getValueSetIndex(val) { let count = 0 for (const [key, values] of Object.entries(sets)) { if (values.includes(val)) { return count; } count += 1 } return null } console.log(getValueSetIndex(4)) console.log(getValueSetIndex(20))<\/code><\/pre>

"

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}
const needle = 5;
Object.values(sets).findIndex(a => a.find(b => b === needle))

returns position number or -1返回位置编号或 -1

const keyIndex = (obj, value) => {
  const index = Object.keys(obj).findIndex(key => obj[key].includes(value));
  return index > -1 ? index : null;
}
console.log(keyIndex(sets, 8));

I can see where you're coming from.我可以看到你来自哪里。 It's often useful to consider how you might eliminate for loops even if you end up using them.即使最终使用它们,考虑如何消除 for 循环通常也很有用。

How do you like this version?:你觉得这个版本怎么样?:

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

const newGetValueSetIndex = val => {
  const result = Object.values(sets)
    .findIndex(
      values => values.includes(val)
    )
  return result === -1 
    ? null 
    : result
}

console.log(newGetValueSetIndex(4))
console.log(newGetValueSetIndex(20))

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

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