Form Object from string in JavaScript


We are required to write a function that takes in a string as the first and the only argument and constructs an object with its keys based on the unique characters of the string and value of each key being defaulted to 0.

For example −

// if the input string is:
const str = 'hello world!';
// then the output should be:
const obj = {"h": 0, "e": 0, "l": 0, "o": 0, " ": 0, "w": 0, "r": 0, "d": 0, "!": 0};

So, let’s write the code for this function −

Example

const str = 'hello world!';
const stringToObject = str => {
   return str.split("").reduce((acc, val) => {
      acc[val] = 0;
      return acc;
   }, {});
};
console.log(stringToObject(str));
console.log(stringToObject('is it an object'));

Output

The output in the console will be −

{ h: 0, e: 0, l: 0, o: 0, ' ': 0, w: 0, r: 0, d: 0, '!': 0 }
{ i: 0, s: 0, ' ': 0, t: 0, a: 0, n: 0, o: 0, b: 0, j: 0, e: 0, c: 0 }

Updated on: 25-Aug-2020

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements