javascript - 如何添加名称并将数组值转换为 JSON?

标签 javascript arrays json

我有一个数组,如下所示:

["1", "hello1@example.com", "user111", "something1"],
["2", "hello2@example.com", "user222", "something2"],
["3", "hello3@example.com", "user333", "something3"],
...
["N", "helloN@example.com", "userNNN", "somethingN"]

如何将其转换为 JSON,如下所示:

{ 
  "order" : "1" 
, "email": "hello1@example.com" 
, "username": "user111" 
, "note": "something1" 
},
{ 
  "order" : "2"
, "email": "hello2@example.com"
, "username": "user222" 
, "note": "something2"
},
{ 
  "order" : "3" 
, "email": "hello3@example.com" 
, "username": "user333" 
, "note": "something3" 
}, 

... 

{ 
  "order" : "N" 
, "email": "helloN@example.com" 
, "username": "userNNN" 
, "note": "somethingN" 
}

我正在自学 JavaScript,因此如果您能推荐类似的案例或文档来了解更多信息,我将不胜感激。

谢谢。

最佳答案

您可以通过多种方式做到这一点,例如使用经典的 for 循环。

我目前喜欢的方式是使用 Array.map:

array = [
    ["1", "hello1@example.com", "user111", "something1"],
    ["2", "hello2@example.com", "user222", "something2"],
    ["3", "hello3@example.com", "user333", "something3"],
    ...
    ["N", "helloN@example.com", "userNNN", "somethingN"]
];

var arr2 = array.map(function(el, i) {
    return {
        order: el[0],
        email: el[1],
        username: el[2],
        note: el[3]
    };
});

参见here供引用。里面有很多很多好东西。

关于javascript - 如何添加名称并将数组值转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36073158/

相关文章:

javascript - 数据准备好后如何渲染组件?

php - 从数组中获取指定行

java - 如何将一些数据放入数组变量并作为 JSONarray 发布?

php - 在 PHP foreach 的脚本中回显 JSON.parse 时,如何避免语法错误?

javascript - 在 MongoDB 中使用嵌套属性查找文档

ruby - 如何使用 Sinatra 和 DataMapper 解析 json 并将该数据写入数据库

javascript - Node js核心模块可以在浏览器上移植吗

javascript - 编写此代码的更简洁方法[限制 <input> 上的字符]

C++在构造函数中初始化一个非静态指针数组

javascript - JavaScript 重新路由的 MVC 异常