Home > Software design >  Convert string into key-value pairs in an object in java script
Convert string into key-value pairs in an object in java script

Time:05-28

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

CodePudding user response:

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}

CodePudding user response:

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);

CodePudding user response:

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:

  • Related