如何获取序列号的特定键数

有一个带有item_description_键后缀索引的动态对象。除了这些键之外,还有其他不同的键。


const input = {

  ...

  item_description_1: "1"

  item_description_2: "2"

  item_description_3: "3"

  ...

}

我怎样才能得到钥匙的数量item_description_?上例中的预期结果应为 3。


动漫人物
浏览 97回答 3
3回答

qq_花开花谢_0

您可以使用Object.keys将对象的所有键放入数组中;然后过滤以开头的键item_description并计算结果数组的长度:const input = {  another_key: 'x',  item_description_1: "1",  item_description_2: "2",  item_description_3: "3",  something_else: 4}const cnt = Object.keys(input)  .filter(v => v.startsWith('item_description'))  .length;console.log(cnt);如果您的浏览器不支持startsWith,您可以随时使用正则表达式,例如.filter(v => v.match(/^item_description/))

慕雪6442864

const keyPrefixToCount = 'item_description_';const count = Object.keys(input).reduce((count, key) => {  if (key.startsWith(keyPrefixToCount)) {    count++  }  return count;}, 0)console.log(count) // 3 for your input您可能应该将前缀删除到变量中。编辑:根据 VLAZ 评论,startsWith会更准确

慕盖茨4494581

我认为使用正则表达式也是一个不错的选择,只需多两行:const input = {  item_descrip3: "22",  item_description_1: "1",  item_description_2: "2",  item_description_3: "3",  test22: "4"}const regex = /^item_description_[1-9][0-9]*$/let result = Object.keys(input).filter(item => regex.test(item))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript