亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取序列號的特定鍵數

如何獲取序列號的特定鍵數

動漫人物 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條經驗 獲得超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/))


查看完整回答
反對 回復 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 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號