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
Selected Reading
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' } Advertisements
