如何使用startsWith筛选并获取每个对象键的值?

3 javascript node.js

我试图通过获取每个键开头checkpoint并输出其值来过滤对象。目前,我只能输出键,而不是值。下面,我有一个简单的对象。我正在使用过滤器和startsWith。我该如何获取这些值?

var data = {
  practicals: '0',
  checkpoint01: '0',
  checkpoint02: '0',
  checkpoint03: '0',
  checkpoint04: '0',
  checkpoint05: '0',
  checkpoint06: '0',
  checkpoint07: '0',
  checkpoint08: '0',
  checkpoint09: '0',
  checkpoint10: '0',
  total: '0'
}

var res = Object.keys(data).filter(v => v.startsWith('checkpoint'))

console.log(res)

// This is the current output: ["checkpoint01", "checkpoint02", "checkpoint03", "checkpoint04", "checkpoint05", "checkpoint06", "checkpoint07", "checkpoint08", "checkpoint09", "checkpoint10"]

// This is the expected output I want: [ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' ]
Run Code Online (Sandbox Code Playgroud)

zma*_*mag 6

Array.prototype.map与data变量一起使用。

var data = {
  practicals: '0',
  checkpoint01: '0',
  checkpoint02: '0',
  checkpoint03: '0',
  checkpoint04: '0',
  checkpoint05: '0',
  checkpoint06: '0',
  checkpoint07: '0',
  checkpoint08: '0',
  checkpoint09: '0',
  checkpoint10: '0',
  total: '0'
}

var res = Object.keys(data).filter(v => v.startsWith('checkpoint')).map(e => data[e])

console.log(res)
Run Code Online (Sandbox Code Playgroud)


Cod*_*iac 3

另一种选择是使用测试,并i标记是否需要不区分大小写

/^checkpoint/i
Run Code Online (Sandbox Code Playgroud)
  • ^- 字符串的开头
  • checkpoint- 匹配单词检查点

如果需要匹配单词检查点后的数字范围,可以扩展模式

 `/^checkpoint[0-6]?/`
Run Code Online (Sandbox Code Playgroud)
  • [0-6]?- 这将允许 0 到 6 之间的任何数字(可选)