

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
- Related Questions & Answers
- Constructing an object from repetitive numeral string in JavaScript
- Split array entries to form object in JavaScript
- Join arrays to form string in JavaScript
- How to create JavaScript Date object from date string?
- Code to construct an object from a string in JavaScript
- HTML DOM Form object
- Trim and split string to form array in JavaScript
- HTML DOM Object form Property
- Recursive string parsing into object - JavaScript
- Can form target array from source array JavaScript
- Creating String Object from Character Array in Java
- Can one string be repeated to form other in JavaScript
- Extract properties from an object in JavaScript
- Can part of a string be rearranged to form another string in JavaScript
- Create array from JSON object JavaScript
Advertisements