Search code examples
javascriptreactjsarraysjsonconverters

how to convert string array of objects to array of objects


I have an array that I want to convert but I have no idea how to do it

how can i convert this array

const a = ['{/run:true}', '{/sleep:false}'];

in this array

const b = [{'/run':true}, {'/sleep':false}];

Solution

  • Using map and a regular expression:

    const a = ['{/run:true}', '{/sleep:false}'];
    const b = a.map(s => {
      const [_,k,v] = s.match(/\{(.+):(.+)}/);
      return {[k]: JSON.parse(v)};
    });
    console.log(b);

    Or other way is to run a sting replacement and JSON.parse

    const a = ['{/run:true}', '{/sleep:false}'];
    const b = JSON.parse("[" + a.toString().replace(/\{([^:]+)/g, '{"$1"') + "]");
    console.log(b);