
- 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
Transforming array to object JavaScript
Suppose we have an array of strings like this −
const arr = [ 'type=A', 'day=45' ];
We are required to write a JavaScript function that takes in one such array. The function should construct an object based on this array. The object should contain a key/value pair for each string in the array.
For any string, the part before '=' becomes the key and the part after it becomes the value.
Example
const arr = [ 'type=A', 'day=45' ]; const arrayToObject = (arr = []) => { const obj = {}; for (let i = 0; i < arr.length; i++) { let currentItem = arr[i].split('='); let key = currentItem[0]; let value = currentItem[1]; obj[key] = value; }; return obj; }; console.log(arrayToObject(arr));
Output
And the output in the console will be −
{ type: 'A', day: '45' }
- Related Articles
- Transforming array of numbers to array of alphabets using JavaScript
- Object to array - JavaScript
- Transforming Problems
- Formatting JavaScript Object to new Array
- Convert array of object to array of array in JavaScript
- How to print object array in JavaScript?
- How to convert array to object in JavaScript
- Group by JavaScript Array Object
- Converting a JavaScript object to an array of values - JavaScript
- Manipulate Object to group based on Array Object List in JavaScript
- From JSON object to an array in JavaScript
- Convert object of objects to array in JavaScript
- Split array entries to form object in JavaScript
- Convert object to array of objects in JavaScript
- Converting object to 2-D array in JavaScript

Advertisements