I get a JSON object from PHP that holds multiple rows like this:
id | type | amount| age
1 | abc | 1 | 1
2 | def | 2 | 1
3 | def | 4 | 2
4 | def | 13 | 3
I run it through JavaScript:
$.ajax({
type: 'POST',
url: "test.php",
dataType: 'json',
success: function (data) {
var arr = [];
for (var i = 0; i < data.length; i++) {
arr[data[i].type][data[i].age] = data[i].ammount;
}
}
});
The idea is to get array that looks like this:
arr[def][1] = 2
arr[def][2] = 4
arr[def][3] = 13
arr[abc][1] = 1
arr[abc][2] = 0 // note that this one is just empty because it was not declared from json data.
Unfortunately I get an error:
Uncaught TypeError: Cannot set property '1' of undefined
1 is [data[i].age]
and if I change its value error appears with other number.
You should do:
var arr = {};
for (var i = 0; i < data.length; i++) {
var type = data[i].type,
age = data[i].age,
amount = data[i].ammount;
if(!arr[type]) arr[type] = {}; //Create arr[type] if it doesn't exist
arr[type][age] = amount;
}
You could fill the empty cells with 0
, but I'd better advise to do this for reading:
//returns the value or 0
function readArr(arr, type, age){
if(!arr[type]) return 0;
return arr[type][age] || 0;
}
Then, instead of reading with arr["abc"][2]
, you'd read with readArr(arr, "abc", 2)
.
(If you prefer, of course you can avoid declaring a function but use its logic inline, you'd do something like (arr["abc"] ? arr["abc"][2] || 0 : 0)
)
Cheers, from La Paz, Bolivia
I think that's because arr['abc']
(or whatever the key is) is still undefined to be an array (or JSON object) when you set its abc
property or key.
var arr = [];
for (var i = 0; i < data.length; i++) {
if (!arr[data[i].type]) {
arr[data[i].type] = [];
}
arr[data[i].type][data[i].age] = data[i].ammount;
}
Or if you want to use JSON objects
var arr = {};
for (var i = 0; i < data.length; i++) {
if (!arr[data[i].type]) {
arr[data[i].type] = {};
}
arr[data[i].type][data[i].age] = data[i].ammount;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.