jquery - Javascript object sort works only sometimes -
my ajax call returns javascript object sometimes sortable. because literally works , other times not. not know why. when not work this.
uncaught typeerror: cars.sort not function
i have specified return datatype json. console.log(typeof cars)
always return object
regardless of whether sort works. since inside success statement, safe assume cars loaded everytime therefore not async issue. read answer , decided try [].sort.call(cars).sort(sort_timestamp)
not work. lost why cars.sort
works , not always. sort_timestamp
function sorts timestamp field of car object.
$.ajax({ url: url, datatype: 'json', success: function (cars) { console.log(typeof cars); // prints word 'object' cars.sort(sort_timestamp); // tried these well. work // cars.sort((a, b) => a.timestamp - b.timestamp); // [].sort.call(cars).sort(sort_timestamp); } });
sort
method of array []
, not object {}
.
to solve problem have 2 options:
fix back-end service make sure return
array
wanted sortconvert
object
array
to safely check if variable object
cannot use typeof
returns object
both array , object
types
use: object.prototype.tostring.call( thevariableyouwanttobechecked )
$.ajax({ url: url, datatype: 'json', success: function (cars) { // check if cars object if (object.prototype.tostring.call(cars) == "[object object]") { var result = []; var keys = object.keys(cars); // convert array; (var = 0; < keys.length; i++) { var key = keys[i]; result.push(cars[key]); } cars = result; // sort cars.sort(); } } });
hope helps
Comments
Post a Comment