1

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

3
  • What did you try so far? Commented Jun 5, 2015 at 13:38
  • possible duplicate of Convert Array to Object Commented Jun 5, 2015 at 13:38
  • I tried : var myJsonString = JSON.stringify(A); var obj = JSON.parse(myJsonString); console.log(obj); Commented Jun 5, 2015 at 13:41

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's clever, +1, didnt' think of that, but it does assume everything is always quoted with double quotes and is valid JSON when stringified.
0

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

2 Comments

Thanks Adeneo for your quick answer, but the object have an additional '' , exemple : '"key"':'"value"'
Well, that's because you have quotes inside quotes, I've removed them for you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.