mo.dhouibi
mo.dhouibi

Reputation: 595

How I can convert array to object in Javascript

I am trying to convert in Javascript an array

A=['"age":"20"','"name":"John"','"email":"[email protected]"'];

to object

O={"age":"20","name":"John","email":"[email protected]"}.

How I can do this. Thanks

Upvotes: 1

Views: 111

Answers (3)

Pankaj Shimpi
Pankaj Shimpi

Reputation: 41

Try this:

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

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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":"[email protected]"'];

var temp = "{" + A.toString() + "}";
var theObj = JSON.parse(temp);
console.log(theObj);

Upvotes: 1

adeneo
adeneo

Reputation: 318182

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

var A = ['"age":"20"','"name":"John"','"email":"[email protected]"'];

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>';

Upvotes: 0

Related Questions