Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 ?
Using reduce() Method
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
{ 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
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 }
Using Set for Unique Characters
const stringToObjectUnique = str => {
const uniqueChars = [...new Set(str)];
const obj = {};
uniqueChars.forEach(char => {
obj[char] = 0;
});
return obj;
};
console.log(stringToObjectUnique('hello'));
console.log(stringToObjectUnique('programming'));
{ h: 0, e: 0, l: 0, o: 0 }
{ p: 0, r: 0, o: 0, g: 0, a: 0, m: 0, i: 0, n: 0 }
Key Points
- The reduce() method creates an object by iterating through each character
- Duplicate characters will overwrite the same key, maintaining uniqueness
- Using Set ensures only unique characters are processed
- All values are initialized to 0 as specified
Conclusion
Creating objects from strings is straightforward using reduce(), for...of loops, or Set for unique characters. The reduce() method provides the most concise solution for this task.
Advertisements
