繁体   English   中英

如何对对象数组进行分组和排序

[英]how to group and sort an array of objects

我得到了一个对象数组

const users= [{
Location: {
  label: "aa",
  value: "aa"
},
Name: "test7"
id: "002"
},
Location: {
  label: "aa",
  value: "aa"
},
Name: "test4"
id: "003"
},

{
Location: {
  label: "ss",
  value: "ss"
},
Name: "test4"     
id: "004"
}]

我想先使用 Location.lable 然后使用 Name(升序)对数组进行排序

这是我已经完成的工作,但它不起作用

const dynamicSort = property => {
var sortOrder = 1;
if (property[0] === "-") {
  sortOrder = -1;
  property = property.substr(1);
}
return function(a, b) {
  var result;
  if (property === "deviceLocation")
    result =
      a[property].label < b[property].label
        ? -1
        : a[property].label > b[property].label
        ? 1
        : 0;
  else
    result =
      a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
  return result * sortOrder;
};
};
users.sort(dynamicSort("deviceLocation"))

结果应该是这样的:

const users= [{
  Location: {
  label: "aa",
  value: "aa"
},
Name: "test4"
id: "003"
},

Location: {
  label: "aa",
  value: "aa"
},
Name: "test7"
id: "002"
},

{
Location: {
  label: "ss",
  value: "ss"
},
Name: "test4"     
id: "004"
}]

如何首先使用 Location.label 然后使用 Name 对数组对象进行排序。 我试过 lodash _.groupBy 和之后的排序,但它没有用

首先,您应该在问题中使用 JSON 或 JavaScript 对象。

然后,您可以创建一个排序函数,该函数首先对用户所在位置的标签进行排序,然后是用户的姓名。

 console.log(getUsers().sort(userComparator)); function userComparator(userA, userB) { let diff = userA.Location.label.localeCompare(userB.Location.label); return diff === 0 ? userA.Name.localeCompare(userB.Name) : diff; } function getUsers() { return [{ "Location": { "label": "colombo", "value": "colombo" }, "Name": "test7", "id": "002" }, { "Location": { "label": "jaffna", "value": "jaffna" }, "Name": "test4", "id": "004" }, { "Location": { "label": "colombo", "value": "colombo" }, "Name": "test4", "id": "003" }]; }
 .as-console-wrapper { top: 0; max-height: 100% !important; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM