[英]Convert string into key-value pairs in an object in java script
I have a string.我有一个字符串。
Input let s = aaabccddd输入let s = aaabccddd
I want to convert this string to key-> value pairs in an obj.我想将此字符串转换为 obj 中的键-> 值对。
output let obj = { a:3, b:1, c:2, d:3 }输出让 obj = { a:3, b:1, c:2, d:3 }
I know how to make keys but confuse about the value please give a javascript solution thankyou我知道如何制作钥匙,但对价值感到困惑,请提供 javascript 解决方案,谢谢
Just loop over the string and increment a counter in a seperate object for each character.只需遍历字符串并为每个字符在单独的对象中增加一个计数器。
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}
You can use Function.prototype.call to invoke the Array.prototype.reduce method on the string and group the characters by their occurrences.您可以使用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);
Other relevant documentations:其他相关文件:
This can be done with Array.reduce()
as follows:这可以使用
Array.reduce()
来完成,如下所示:
let s = 'aaabccddd'; let result = [...s].reduce((o, c) => { o[c] = (o[c] | 0) + 1; return o; }, {}); console.log(result);
You can use String.match()
with RegExp to get the repeated occurrences of each character, map them toan array of [character, occurrences]
pairs, and convert the list of pairs to an object using Object.fromEntries()
:您可以使用
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)
Or use String.matchAll()
with Array.from()
to create the list of entries:或者使用
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.