简体   繁体   English

如何在Javascript中将数组转换为对象

[英]How I can convert array to object in Javascript

I am trying to convert in Javascript an array我正在尝试在 Javascript 中转换一个数组

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谢谢

Since the keys are quoted, you can take advantage of JSON.parse .由于键被引用,您可以利用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);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM