
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 }
- Related Articles
- JavaScript construct an array with elements repeating from a string
- Constructing an object from repetitive numeral string in JavaScript
- Form Object from string in JavaScript
- Converting string to MORSE code in JavaScript
- From JSON object to an array in JavaScript
- How to construct a JSON object from a subset of another JSON object in Java?
- How to return an object from a JavaScript function?
- Construct string via recursion JavaScript
- How to represent the source code of an object with JavaScript Arrays?
- How to create an element from a string in JavaScript?
- How to create JavaScript Date object from date string?
- Transform data from a nested array to an object in JavaScript
- Building an array from a string in JavaScript
- How to set a String as a key for an object - JavaScript?
- Extract properties from an object in JavaScript

Advertisements