希望這不會被關閉,我找不到任何合適的問題。
- 前綴是一個變數
- 后綴始終是單詞
Value - 結果值的第一個字母應小寫
到目前為止的代碼,缺少第一個字母的小寫字母:
// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
// Wanted: { duration: 3000, position: 'bottom' }
const options = Object.keys(element.dataset)
.filter(k => k.startsWith(prefix))
.reduce((prev, curr) => ({
...prev,
[curr.slice(prefix.length).replace(/(Value)$/, '')]: element.dataset[curr]
}), {});
uj5u.com熱心網友回復:
只需添加
.toLowerCase()
后
.replace(/(Value)$/, '')
這里:
// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
const options = Object.keys(element.dataset)
.filter(k => k.startsWith(prefix))
.reduce((prev, curr) => ({
...prev,
[curr.slice(prefix.length).replace(/(Value)$/, '').toLowerCase()]: element.dataset[curr]
}), {});
console.log(options);
輸出:
{ duration: 3000, position: 'bottom' }
uj5u.com熱心網友回復:
這可以在一個陳述句中,以一種復雜(難以閱讀)的方式使用slice(),replace()和來完成toUpperCase()。原始字串保持原樣:
let str = 'hellorandomWORDValue';
const prefix = 'hello';
const str2 = str.replace(prefix, "").slice(0,-5)[0].toUpperCase() str.replace(prefix, "").slice(0,-5).slice(1)
console.log(str);
console.log(str2);
slice(0,5)-> 洗掉最后 5 個字母,因此基本上洗掉了Value后綴。
replace(prefix,"")-> 替換變數 string 的第一個實體prefix。所以基本上洗掉了前綴。
[0].toUpperCase()-> 取出第一個字符并將其變為大寫。
.slice(1)-> 取出字串的其余部分(從第一個索引開始)。基本上,第一個字符之后的其余字串。
const options = Object.keys(element.dataset)
.filter(k => k.startsWith(prefix))
.reduce((prev, curr) => ({
...prev,
[curr.replace(prefix, "").slice(0,-5)[0].toUpperCase() curr.replace(prefix, "").slice(0,-5).slice(1)]: element.dataset[curr]
}), {});
uj5u.com熱心網友回復:
下面的代碼片段可能有助于您的解決方案。
const obj = { toastDurationValue: 3000, toastPositionValue: 'bottom' }
const prefix = 'toast';
Object.keys(obj).forEach(key => {
obj[key] = obj[key.substring(0, key.lastIndexOf('Value')).replace(prefix, '').toLowerCase()] = obj[key];
delete obj[key];
})
console.log(obj);
uj5u.com熱心網友回復:
出于某種原因,映射條目而不是減少物件對我來說感覺好一點:
const simplify_key = (key, prefix_length) =>
key[prefix_length].toLowerCase() key.substring(prefix_length 1, key.length - 5);
const extract_options = (dataset, prefix = 'toast') =>
Object.fromEntries(
Object.entries(dataset)
.filter(([key]) => key.startsWith(prefix))
.map(([key, val]) => [simplify_key(key, prefix.length), val])
);
console.log(extract_options({
toastDurationValue: 3000,
toastPositionValue: 'bottom',
toastMoreTermsValue: 'thing',
otherDataItem: 'wibble'
}));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472639.html
標籤:javascript
上一篇:變數不會變成全域變數
下一篇:停止運行影片計數器腳本
