我有一个数组,如下所示:
["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/