[英]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.