
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Array to Object by Splitting Properties in 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' }
Advertisements