3 回答

TA贡献1835条经验 获得超7个赞
您可以使用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/))

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

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))
添加回答
举报