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))
添加回答
舉報