Convert a SQL table to a JSON object and sort it

Want to convert a SQL table to a javascript object and sort it? This is one way to do this. First, create an array of objects. Each object represents one row. Create a key for the row index (starting at 0) and a key that contains an array of the column values. Now we have converted an SQL table to a simple JSON object.

Now we can simply sort the array using the arr.sort([compareFunction]) function. (see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) . That’s it. Below a complete example. Or goto jsfiddle .

var queryObject = [
	{"row":0,"columns":["Washington",	157,1090,1003]},
	{"row":1,"columns":["Moscow",		228,531,315]},
	{"row":2,"columns":["London",		293,152,432]},
	{"row":3,"columns":["Tokyo",		953,996,750]},
	{"row":4,"columns":["Beijing",		1030,919,311]}
];

var sortByColumnIndex = 2; /* Third column*/

queryObject.sort(function(a,b){return (a.columns[sortByColumnIndex] > b.columns[sortByColumnIndex] ? -1 : 1)});

console.log(queryObject);
/*
[
	{columns: ["Washington", 157, 1090, 1003],row: 0}, 
	{columns: ["Tokyo", 	953, 996, 750],row: 3}, 
	{columns: ["Beijing", 1030, 919, 311],row: 4},
	{columns: ["Moscow", 228, 531, 315],row: 1}, 
	{columns: ["London", 293, 152, 432],row: 2}
]
*/

Leave a Reply

Your email address will not be published. Required fields are marked *