- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating an array using a string which contains the key and the value of the properties - JavaScript
Suppose, we have a special kind of string like this −
const str ="Integer,1 Float,2.0
Boolean,True Integer,6
Float,3.66 Boolean,False";
We are required to write a JavaScript function that converts the above string into the following array, using the String.prototype.split() method −
const arr = [ { "Integer":1, "Float":2.0 }, { "Boolean":true, "Integer":6 }, { "Float":3.66, "Boolean":false } ];
We have to use the following rules for conversion −
---
marks the end of an object --- one whitespace terminates one key/value pair within an object --- ',' one comma separates the key from value of an object
Example
Following is the code −
const str ="Integer,1 Float,2.0
Boolean,True Integer,6
Float,3.66 Boolean,False"; const stringToArray = str => { const strArr = str.split('
'); return strArr.map(el => { const elArr = el.split(' '); return elArr.map(elm => { const [key, value] = elm.split(','); return{ [key]: value }; }); }); }; console.log(stringToArray(str));
Output
This will produce the following output in console −
[ [ { Integer: '1' }, { Float: '2.0' } ], [ { Boolean: 'True' }, { Integer: '6' } ], [ { Float: '3.66' }, { Boolean: 'False' } ] ]
Advertisements