Code to construct an object from a 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!';

Output

Then the output object should be −

const obj = { "h": 0, "e": 0, "l": 0, "o": 0, " ": 0, "w": 0, "r": 0, "d": 0, "!": 0 };

Example

Let’s write the code for this function −

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 −

{ 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: 17-Oct-2020

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements