Transforming array to object JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.


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;


And the output in the console will be −

{ type: 'A', day: '45' }
Updated on 21-Nov-2020 06:24:35