Sorting Json data based on a field

梦想与她 提交于 2019-12-11 05:39:36

问题


I have a Json data that I need to sort before display it. My Json is as below. I need to sort them based on the ColumnLocation.

[{
  "Name": "PieChart",
  "Id": "1",
  "ColumnLocation": "0",
  "RowLocation": "0"
}, {
  "Name": "Calendar",
  "Id": "2",
  "ColumnLocation": "1",
  "RowLocation": "0"
}, {
  "Name": "FavouriteFilter",
  "Id": "3",
  "ColumnLocation": "2",
  "RowLocation": "0"
}, {
  "Name": "FilterResults",
  "Id": "4",
  "ColumnLocation": "0",
  "RowLocation": "1"
}, {
  "Name": "Watched",
  "Id": "5",
  "ColumnLocation": "1",
  "RowLocation": "1"
}]

i.e the sorted array should have items in following fashion

col : 0, row 0
col : 0, row 1
col : 1, row 0
col : 1, row 1

回答1:


No need for lodash/underscore. You can use Array.prototype.sort: Since your values are strings, you must first parse them into numbers and then compare:

let a = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}]

let sorted = a.sort((a, b) => parseInt(a.ColumnLocation) - parseInt(b.ColumnLocation));

console.log(sorted);



回答2:


Short and sweet.

let arr = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}]

arr.sort ( ( a, b ) => { return parseInt ( a.ColumnLocation ) > parseInt ( b.ColumnLocation ) } );

console.log ( arr );

Note that if you don't convert to a number, the sorting can not be what you expect.




回答3:


Why not use _.sortBy ( http://underscorejs.org/#sortBy ) ?

var mysortedarray = _.sortBy(myarray, 'ColumnLocation');


来源:https://stackoverflow.com/questions/43398137/sorting-json-data-based-on-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!