I'd like to create a multidimensional array using a loop in jQuery/JS. Is it possible to use the next available key instead of setting it manually?
jsonFromPhp contains something like this:
0 {first_name: "Tom", last_name: "Smith", location: "London"}
1 {first_name: "Max", last_name: "Muster", location: "Zurich"}
2 {first_name: "Joanne", last_name: "Kate", location: "London"}
...
Here is the loop:
jsonFromPhp.forEach((row, i) => {
if (row['location'] == 'London') {
firstKey = 0;
} else {
firstKey = 1;
}
row.forEach((singleData, n) => {
pushedArray[firstKey][] = singleData[n]; // doesn't work, I have set the index manually (with i for example). But then I have an array like 0, 2, 5 etc. and I need 0, 1, 2
});
});
Expected Result:
0 Array (1)
0 ["Tom", "Smith", "London"] (3)
1 ["Joanne", "Kate", "London"] (3)
...
1 Array (1)
0 ["Max", "Muster", "Zurich"] (3)
...
and not (if I set pushedArray[firstKey][i])
0 Array (1)
0 ["Tom", "Smith", "London"] (3)
2 ["Joanne", "Kate", "London"] (3)
...
1 Array (1)
1 ["Max", "Muster", "Zurich"] (3)
...
or
0 Array (1)
0 ["Tom", "Smith", "London", "Joanne", "Kate", "London"] (6)
1 Array (1)
1 ["Max", "Muster", "Zurich"] (3)
...