[英]Convert string into key-value pairs in an object in java script
我有一個字符串。
輸入let s = aaabccddd
我想將此字符串轉換為 obj 中的鍵-> 值對。
輸出讓 obj = { a:3, b:1, c:2, d:3 }
我知道如何制作鑰匙,但對價值感到困惑,請提供 javascript 解決方案,謝謝
只需遍歷字符串並為每個字符在單獨的對象中增加一個計數器。
function countOccurences(string) {
const result = {};
for (const character of string) {
if (typeof result[character] === 'undefined') {
result[character] = 0;
}
result[character]++;
}
return result;
}
console.log(countOccurences('aaabccddd'));
//=> {a: 3, b: 1, c: 2, d: 3}
您可以使用Function.prototype.call在字符串上調用Array.prototype.reduce方法,並按出現的字符對字符進行分組。
const str = "aaabccddd", res = Array.prototype.reduce.call( str, (r, s) => { r[s] ??= 0; r[s] += 1; return r; }, {} ); console.log(res);
其他相關文件:
這可以使用Array.reduce()
來完成,如下所示:
let s = 'aaabccddd'; let result = [...s].reduce((o, c) => { o[c] = (o[c] | 0) + 1; return o; }, {}); console.log(result);
您可以使用String.match()
和 RegExp 來獲取每個字符的重復出現,將它們映射到[character, occurrences]
對的數組,並使用Object.fromEntries()
將對的列表轉換為對象:
const fn = s => Object.fromEntries(s .match(/(.)\1*/g) // find all recuring matches .map(str => [str[0], str.length]) // create an array of [character, occurrences] ) const s = 'aaabccddd' const result = fn(s) console.log(result)
或者使用String.matchAll()
和Array.from()
創建條目列表:
const fn = s => Object.fromEntries( Array.from( s.matchAll(/(.)\1*/g), // find all recuring matches ([{ length }, c]) => [c, length] // create an array of [character, occurrences] ) ) const s = 'aaabccddd' const result = fn(s) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.