1

I am trying to convert in Javascript an array

A=['"age":"20"','"name":"John"','"email":"john@email.com"'];

to object

O={"age":"20","name":"John","email":"john@email.com"}.

How I can do this. Thanks

mo.dhouibi
  • 565
  • 1
  • 4
  • 18

3 Answers3

1

Since the keys are quoted, you can take advantage of JSON.parse. You can just make the array a string, wrap it in curly brackets, and parse it.

var A = ['"age":"20"', '"name":"John"', '"email":"john@email.com"'];

var temp = "{" + A.toString() + "}";
var theObj = JSON.parse(temp);
console.log(theObj);
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Should be straight forward, just iterate and split on the colon

var A = ['"age":"20"','"name":"John"','"email":"john@email.com"'];

var O = {};

A.forEach(function(item) {
    var parts = item.split(':').map(function(x) { return x.trim().replace(/\"/g,'') });
    
    O[parts[0]] = parts[1];
});

document.body.innerHTML = '<pre>' + JSON.stringify(O, null, 4) + '</pre>';
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Try this:

const A = ['"age":"20"', '"name":"John"', '"email":"john@email.com"'];
const result = A.reduce((res, i) => {
    let s = i.split(':');
    return {...res, [s[0]]: s[1].trim().replace(/\"/g, '')};
}, {});
console.log(result);