Converting array to object by splitting the properties - JavaScript


We have an array of string literals in which each element has a dash (-), The property key is present to the left of dash and its value to the right. A sample input array would look something like this −

const arr = ["playerName-Kai Havertz", "age-21", "nationality-German", "postion-CAM", "languages-German,English,Spanish", "club-Chelsea"];

We are required to write a function that splits these strings and form an object out of this array.

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

Example

Following is the code −

const arr = ["playerName-Kai Havertz", "age-21", "nationality-German",
"postion-CAM", "languages-German,English,Spanish", "club-Chelsea"];
const arrayToObject = arr => {
   const obj = {};
   arr.forEach(string => {
      const [key, value] = string.split("-");
      obj[key] = value;
   });
   return obj;
};
console.log(arrayToObject(arr));

Output

This will produce the following output in console −

{
   playerName: 'Kai Havertz',
   age: '21',
   nationality: 'German',
   postion: 'CAM',
   languages: 'German,English,Spanish',
   club: 'Chelsea'
}

Updated on: 18-Sep-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements