javascript - Return -1 if JSON Array is NULL works only in some data -
i wanted to:
- return
-1
ifdata
(array) null or empty - if data not null , if array has
rain_value
property wanted 2nd index value of array based on length
below snippet of code:
success: function (data) { //console.log(data); $.map(data, function (e) { var max = -1; var dev_id = e.dev_id; var data = e.data; var r; if (data) { (var j = 0; j < data.length; j++) { r = parsefloat(data[j].rain_value) || 0; arr[j] = parsefloat(r); } } if (arr.length) { max = arr[1] * 4; //max = math.max.apply(math, arr) * 4; } (var k = 0; k < len; k++) { var jsonobj_device_id = jsonobj.features[k].properties.device_id; if (jsonobj_device_id == dev_id) { var namer = "rain_intensity"; var rainvalue = max; jsonobj.features[k].properties[namer] = rainvalue; } } console.log(dev_id + " " + max) }); }
i can't seem figure out why works in data. here's fiddle. thanks!
you assigning empty array value variable arr
outside loop, not within loop. means have data , array populated every following iteration have array values. need clear every time, or declare in loop...
success: function (data) { //console.log(data); $.map(data, function (e) { var max = -1; var dev_id = e.dev_id; var data = e.data; var r; arr = []; // <---- clear array here if (data) { (var j = 0; j < data.length; j++) { r = parsefloat(data[j].rain_value) || 0; arr[j] = parsefloat(r); } } if (arr.length) { max = arr[1] * 4; //max = math.max.apply(math, arr) * 4; } (var k = 0; k < len; k++) { var jsonobj_device_id = jsonobj.features[k].properties.device_id; if (jsonobj_device_id == dev_id) { var namer = "rain_intensity"; var rainvalue = max; jsonobj.features[k].properties[namer] = rainvalue; } } console.log(dev_id + " " + max) }); }
Comments
Post a Comment