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

JavascriptWeb DevelopmentObject Oriented Programming

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'
}
raja
Published on 19-Aug-2020 07:08:49
Advertisements