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

Using Array.reduce() Method

The most efficient approach is to split the string into characters and use the reduce() method to build the object:

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'));
{ 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 }

Using for...of Loop

An alternative approach using a simple loop for better readability:

const stringToObjectLoop = str => {
    const obj = {};
    for (const char of str) {
        obj[char] = 0;
    }
    return obj;
};

console.log(stringToObjectLoop('hello'));
console.log(stringToObjectLoop('javascript'));
{ h: 0, e: 0, l: 0, o: 0 }
{ j: 0, a: 0, v: 0, s: 0, c: 0, r: 0, i: 0, p: 0, t: 0 }

How It Works

Both methods create an object where:

  • split("") converts the string into an array of individual characters
  • reduce() iterates through each character and adds it as a key with value 0
  • Duplicate characters are automatically overwritten, ensuring unique keys only

Conclusion

The reduce() method provides a functional approach to convert string characters into object keys. Both methods effectively handle duplicate characters by maintaining only unique keys with zero values.

Updated on: 2026-03-15T23:19:00+05:30

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements