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' } ]
]

Updated on: 30-Sep-2020

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements