我有一个像这样的数组对象,我想基于_0属性对这个数组进行排序,请用Javascript或Dojo提供一些解决方案

eivgtgni  于 2022-12-08  发布在  Dojo
关注(0)|答案(3)|浏览(145)
[
    {Devices:"All Devices",Groups:"Location/All Locations", id:"table-default00",_0:0},
    {Devices:"All sourecs",Groups:"Location/All Locations", id:"table-default01",_0:1}
]
aiazj4mn

aiazj4mn1#

您可以将一个自定义函数传递给Array#sort方法。该函数的返回值决定元素的顺序。

const data = [{
  Devices: "All Devices",
  Groups: "Location/All Locations",
  id: "table-default00",
  _0: 0
}, {
  Devices: "All sourecs",
  Groups: "Location/All Locations",
  id: "table-default01",
  _0: 1
}];

const result = data.sort((a, b) => a['_0'] - b['_0']);
console.log(result);
62o28rlo

62o28rlo2#

定义用于对数组排序的比较函数。在比较函数中,返回键'_0'的值的差。

function sortMyList(a,b){
  return a['_0']-b['_0'];
}

var list = [{Devices:"All sourecs",Groups:"Location/All Locations", id:"table-default01",_0:3},
            {Devices:"All sourecs",Groups:"Location/All Locations", id:"table-default01",_0:2},
            {Devices:"All sourecs",Groups:"Location/All Locations", id:"table-default01",_0:4},
            {Devices:"All Devices",Groups:"Location/All Locations", id:"table-default00",_0:0}, 
            {Devices:"All sourecs",Groups:"Location/All Locations", id:"table-default01",_0:1}];
console.log(list);
list.sort(sortMyList);
console.log(list);
vecaoik1

vecaoik13#

如果需要按多个列排序并更改升序和降序,则可以使用此常规实现:
第一个

相关问题