Javascript对键值上的对象进行排序的数组 [英] Javascript sort array of objects on key values

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

问题描述

我正在尝试对包含状态键的对象数组进行排序,该状态键具有"online","offline","Busy",因此只想对数组进行排序,以使所有"online"都显示在顶部按忙",然后按离线"

I was trying to sort array of objects which contains status key which has "online","offline","Busy" , so just wanted to sort the array in such a way that all "online" would appear on top followed by "Busy" and then "offline"

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];

arr.sort(function(first, second) {
   if (second.status == "online") return 1;

 });

console.log(arr);

这将仅返回我一个状态:顶部为在线".谢谢

This would return me only status: "online" on the top. Thanks

推荐答案

尝试一下:

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];
           
 var statusOrder = ["online", "busy", "offline"];
 
 arr = arr.sort(function(a, b) { 
     return statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status);
 });

 console.log(arr);

使用ECMAScript6甚至更短:

And even shorter with ECMAScript6:

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];
           
 var statusOrder = ["online", "busy", "offline"];
 
 arr = arr.sort((a, b) => statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status));

 console.log(arr);

这篇关于Javascript对键值上的对象进行排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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