Was it helpful?

Question

Creating an array using a string which contains the key and the value of the properties - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a special kind of string like this −

const str ="Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,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 −

--- \n 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\nBoolean,True Integer,6\nFloat,3.66
Boolean,False";
const stringToArray = str => {
   const strArr = str.split('\n');
   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' } ]
]
raja
Published on 30-Sep-2020 17:07:51
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top