为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

动漫人物 2023-10-20 17:38:53
有一个带有item_description_键后缀索引的动态对象。除了这些键之外,还有其他不同的键。const input = {  ...  item_description_1: "1"  item_description_2: "2"  item_description_3: "3"  ...}我怎样才能得到钥匙的数量item_description_?上例中的预期结果应为 3。
查看完整描述

3 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

您可以使用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/))


查看完整回答
反对 回复 2023-10-20
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

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会更准确


查看完整回答
反对 回复 2023-10-20
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

我认为使用正则表达式也是一个不错的选择,只需多两行:


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


查看完整回答
反对 回复 2023-10-20
  • 3 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信