I would like to convert Json data to an array Javascript, that I can access like using array[0][0], someone can help me please.
[
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "124564",
"Email": "[email protected]"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124564",
"Email": "[email protected]"
}
]
I tried this piece of code but nothing happen , I can't access to a specific(Exemple I would like to have Nom) data in array using for example array[0][1].
Code.js
var data = [
{
"Login": "test1",
"Nom": "test1",
"Prenom": "test1p",
"password": "1267846",
"Email": "[email protected]"
},
{
"Login": "test2",
"Nom": "test2",
"Prenom": "test2p",
"password": "124494",
"Email": "[email protected]"
}
];
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]);
Once parsed, if I try to access it using myArr[0][1], it shows as undefined.
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","[email protected]"],
// ["test2","test2","test2p","124564","[email protected]"]
// ]
If you can rely on es5 functions, you can use Array.prototype.map and Object.keys
var arr = data.map(function(e) {
return Object.keys(e).map(function(k) { return e[k]; });
});
arr;
// [
// ["test1","test1","test1p","124564","[email protected]"],
// ["test2","test2","test2p","124564","[email protected]"]
// ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With