Computer >> Computer tutorials >  >> Programming >> Javascript

Convert string with separator to array of objects in JavaScript


Suppose, we have a string like this −

const str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';

We are required to write a JavaScript function that takes in one such string.

The function should split the string off '|' to separate the option and its value and convert it to an array of objects like this −

const output = [ {
   "option": "Option 1",
   "value": false
   }, {
      "option": "Option 2",
      "value": false
   }, {
      "option": "Option 3",
      "value": false
   }, {
      "option": "Option 4",
      "value": true
   }
];

Example

const str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true'; const stringToObject = (str = '') => {
   const res = [];
   for (let i = 0, a = str.split('|');
   i < a.length; i += 2) {
      const option = a[i], value = JSON.parse(a[i + 1]);
      res.push({ option, value });
   }
   return res;
};
console.log(stringToObject(str));

Output

And the output in the console will be −

[
   { option: 'Option 1', value: false },
   { option: 'Option 2', value: false },
   { option: 'Option 3', value: false },
   { option: 'Option 4', value: true }
]