如何解决根据json中的两个字段排序
我想基于两个字段对json数据进行排序。我想首先基于geo和用户名对数据进行排序我想基于geo进行排序并在geo内对用户进行排序。例如在geo'Europe'中 按字母顺序对用户进行排序,然后按“中东”地理位置
const response = [{Username: "Denisse Morales",Geo: "NSU",Status: "Reaches",month: "May",Week2: 2},{Username: "Chandra Jeevan J",Geo: "US East",Week2: 1},{Username: "Amy Khalil",Geo: "US West",{Username: "Ashuwinth Panneer",Geo: "Europe",month: "June",{Username: "John Joshuva",Week2: 3},{Username: "Jose Alberto",month: "April",{Username: "Dhivya Muthusamy",Week2: 10},{Username: "Faizan Mohammed",Geo: "Middle East",{Username: "Jaison Clinton",Week2: 9}];
response.sort((a,b) => a.Geo.localeCompare(b.Geo));
response.sort((a,b) => a.Username.localeCompare(b.Username));
console.log(response);
解决方法
我想你想要这样的东西
const response = [ { Username: "Denisse Morales",Geo: "NSU",Status: "Reaches",month: "May",Week2: 2,},{ Username: "Chandra Jeevan J",Geo: "US East",Week2: 1,{ Username: "Amy Khalil",Geo: "US West",{ Username: "Ashuwinth Panneer",Geo: "Europe",month: "June",{ Username: "John Joshuva",Week2: 3,{ Username: "Jose Alberto",month: "April",{ Username: "Dhivya Muthusamy",Week2: 10,{ Username: "Faizan Mohammed",Geo: "Middle East",{ Username: "Jaison Clinton",Week2: 9,];
response.sort(
(a,b) => a.Geo.localeCompare(b.Geo) || a.Username.localeCompare(b.Username)
);
console.log(response);
,
您可以比较串联的地理位置和用户名。
const response = [{Username: "Denisse Morales",Week2: 2},{Username: "Chandra Jeevan J",Week2: 1},{Username: "Amy Khalil",{Username: "Ashuwinth Panneer",{Username: "John Joshuva",Week2: 3},{Username: "Jose Alberto",{Username: "Dhivya Muthusamy",Week2: 10},{Username: "Faizan Mohammed",{Username: "Jaison Clinton",Week2: 9}];
response.sort((a,b) => {
return (a.Geo + a.Username) > (b.Geo + b.Username) ? 1 : -1;
});
console.log(response);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。