简体   繁体   中英

Convert string into key-value pairs in an object in java script

I have a string.

Input let s = aaabccddd

I want to convert this string to key-> value pairs in an obj.

output let 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

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.

 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:

 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() :

 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:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM