根据字段对Json数据进行排序 [英] Sorting Json data based on a field

查看:410
本文介绍了根据字段对Json数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Json数据,需要排序才能显示。我的Json如下我需要根据ColumnLocation对它们进行排序。

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


推荐答案

不需要lodash /下划线。您可以使用 Array.prototype.sort
由于你的值是字符串,你必须首先将它们解析成数字,然后比较:

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);

这篇关于根据字段对Json数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆