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.
2 Answers 2
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]"]
// ]
Comments
you have confused with the array and objects. All arrays are objects. but not all objects are arrays. You use "for..in" loop in wrong understanding on array containing objects. If you add more console statements and check, you can understand how it works. Let me give reqd. solution for your scenario.
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 i=0;i<data.length;i++) {
var obj = data[i];
array[i] = new Array();
for(var key in obj) {
array[i].push(obj[key]);
}
}
return array;
}
var array = data_to_array(data);
console.log(array);
Comments
Explore related questions
See similar questions with these tags.
for..inwith an array. What is the expected output?for (var i=0,......datais not JSON, it is itself an array. What are you trying to achieve here?