Skip to content Skip to sidebar Skip to footer

How I Can Convert Array To Object In Javascript

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

Solution 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);

Solution 2:

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

Solution 3:

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

Post a Comment for "How I Can Convert Array To Object In Javascript"