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}];
CodePudding user response:
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);
CodePudding user response:
Created this simple function to do exactly that
const a = ['{/run:true}', '{/sleep:false}'];
// desired output
const b = [{ run: true }, { sleep: false }];
const c = a.map(item => {
const key = item.match(/\w /)[0];
const value = item.match(/true|false/)[0];
return { [key]: value === 'true' };
});
console.log(c);
CodePudding user response:
const a = ['{/run:true}', '{/sleep:false}'];
const output = a.map(item => {
const normalize = item.replaceAll("{", "").replaceAll("}", "")
const splitedStr = normalize.split(':');
const key = splitedStr[0];
const value = splitedStr[1];
return {[key]: value}
})
console.log(output)
CodePudding user response:
const a = ['{/run:true}', '{/sleep:false}'];
const c = a.map(item => {
return {
['/' item.split(':')[1].split('{')[0]]: item.split(':')[1].split('}')[0]
};
});
console.log(c);