【问题标题】:How I can convert array to object in Javascript如何在 Javascript 中将数组转换为对象
【发布时间】:2015-08-20 11:43:29
【问题描述】:

我正在尝试在 Javascript 中转换一个数组

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

反对

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

我怎么能做到这一点。 谢谢

【问题讨论】:

  • 到目前为止你尝试了什么?
  • Convert Array to Object的可能重复
  • 我试过了:var myJsonString = JSON.stringify(A); var obj = JSON.parse(myJsonString); console.log(obj);

标签: javascript arrays types type-conversion


【解决方案1】:

由于引用了键,您可以利用JSON.parse。你可以把数组变成一个字符串,用大括号括起来,然后解析它。

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

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

【讨论】:

  • 这很聪明,+1,没有想到这一点,但它确实假设所有内容始终用双引号引起来,并且在字符串化时是有效的 JSON。
  • 也感谢您的解决方案
【解决方案2】:

应该直截了当,只是在冒号上迭代和拆分

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 的快速回答,但该对象有一个额外的 '' ,例如:'"key"':'"value"'
  • 嗯,那是因为引号中有引号,我已经为您删除了。
【解决方案3】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2015-01-13
    • 2011-04-21
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多