簡體   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