How can I convert an array to an object by splitting strings? JavaScript


Let’s say, we have an array of strings in which each value each element has a dash (-), left to which we have our key and right to which we have our value. Our job is to split these strings and form an object out of this array.

Here is the sample array −

const arr = ["name-Rakesh", "age-23", "city-New Delhi", "jobType-remote",
"language-English"];

So, let’s write the code, it will loop over the array splitting each string and feeding it into the new object

The full code will be −

Example

const arr = ["name-Rakesh", "age-23", "city-New Delhi", "jobType-remote",
"language-English"];
const obj = {};
arr.forEach(string => {
   const [key, value] = string.split("-");
   obj[key] = value;
});
console.log(obj);

Output

The console output for this code will be −

{
   name: 'Rakesh',
   age: '23',
   city: 'New Delhi',
   jobType: 'remote',
   language: 'English'
}

Updated on: 19-Aug-2020

633 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements