gpt4 book ai didi

javascript - 将json多维转换为数组javascript

转载 作者:行者123 更新时间:2023-11-30 05:37:29 24 4
gpt4 key购买 nike

我想将 Json 数据转换为数组 Javascript,我可以像使用数组 [0][0] 一样访问它,请有人帮助我。

[
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "124564",
"Email": "test1@gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124564",
"Email": "test2@gmail.com"
}
]

我尝试了这段代码,但没有任何反应,我无法使用例如数组 [0][1] 访问数组中的特定(示例,我想拥有 Nom)数据。

代码.js

var data = [
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "1267846",
"Email": "test1@gmail.com"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124494",
"Email": "test2@gmail.com"
}
];

function data_to_array(data) {
var array = [];
for (var key in data) {
var value = data[key];
if (typeof value === 'string') {
array[key] = value;
} else {
array[key] = data_to_array(value);
}
}
return array;
}

var array = data_to_array(data);
for(var i in array)
console.log(array[i]);

解析后,如果我尝试使用 myArr[0][1] 访问它,它会显示为未定义。

最佳答案

var arr = [];

for (var i=0, len=data.length, tmp; i<len; i++) {
tmp = [];
for (var k in data[i]) {
if (data[i].hasOwnProperty(k)) {
tmp.push(data[i][k]);
}
}
arr.push(tmp);
}

arr;
// [
// ["test1","test1","test1p","124564","test1@gmail.com"],
// ["test2","test2","test2p","124564","test2@gmail.com"]
// ]

如果可以依赖es5函数,可以使用Array.prototype.map和Object.keys

var arr = data.map(function(e) {
return Object.keys(e).map(function(k) { return e[k]; });
});

arr;
// [
// ["test1","test1","test1p","124564","test1@gmail.com"],
// ["test2","test2","test2p","124564","test2@gmail.com"]
// ]

关于javascript - 将json多维转换为数组javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22805227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com