Javascript 基于字段对Json数据进行排序

Javascript 基于字段对Json数据进行排序,javascript,ecmascript-6,underscore.js,lodash,Javascript,Ecmascript 6,Underscore.js,Lodash,我有一个Json数据,需要在显示之前对其进行排序。我的Json如下所示。我需要根据位置对它们进行排序 [{ "Name": "PieChart", "Id": "1", "ColumnLocation": "0", "RowLocation": "0" }, { "Name": "Calendar", "Id": "2", "ColumnLocation": "1", "RowLocation": "0" }, { "Name": "FavouriteFilt

我有一个Json数据,需要在显示之前对其进行排序。我的Json如下所示。我需要根据位置对它们进行排序

[{
  "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排序的数组应具有以下方式的项

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

无需使用lodash/下划线。您可以使用: 由于您的值是字符串,因此必须首先将它们解析为数字,然后比较:

让a=[{“Name”:“PieChart”,“Id”:“1”,“ColumnLocation”:“0”,“RowLocation”:“0”},{“Name”:“日历”,“Id”:“2”,“ColumnLocation”:“1”,“RowLocation”:“0”},{“Name”:“FilterResults”,“Id”:“4”,“ColumnLocation”:“0”,“RowLocation”:“1”},{“Name”:“wasted”,“Id”:“5”,“ColumnLocation”:“1”,“行位置”:“1”}]
让sorted=a.sort((a,b)=>parseInt(a.ColumnLocation)-parseInt(b.ColumnLocation));
console.log(已排序);
短而甜

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 );
请注意,如果不转换为数字,则排序将无法达到预期效果。

为什么不使用u.sortBy()


没有看到任何json,只看到“以下方式中的项目”。但是,方法是,将json转换为JS对象/数组/无论它们是什么,运行排序(取决于json转换成什么),然后就可以了。json只是一个字符串,要应用典型的排序ALG,必须将其转换(json.parse)@timconolazio Sorry刚刚添加了Json。在下面发布了答案。这种排序可能不稳定:您提供给
sort
的比较函数应该返回一个可以是负数、零或正数的数字,但是这个函数返回的是布尔值,所以永远不会是负值。原语值没有问题,因为它们是无法区分的le。但一般来说,最好像接受的答案中那样进行减法,因为这将导致稳定排序(“稳定”只有在您能够区分与排序条件相等的值,但具有其他属性进行区分时才有意义)。这是一个最佳实践问题。因此在这种用法中,排序没有问题。谢谢。啊,我看到So集团又找到了我。Meh,享受你的DV。事实上,这是设计得更好的比较函数(减法返回数字数据类型)(+1)。
var mysortedarray = _.sortBy(myarray, 'ColumnLocation');