简体   繁体   English

在 JavaScript 中对对象数组进行排序

[英]Sorting an array of objects in JavaScript

I am quite new to objects and I'm trying to sort the following example by 'name' without much success.我对对象很陌生,我试图按“名称”对以下示例进行排序,但没有取得太大成功。

Any help would be appreciated.任何帮助,将不胜感激。

   [{
    "5be471e0-5970-11ea-8e53-3dcfba064c75": {
        "id": "5be471e0-5970-11ea-8e53-3dcfba064c75",
        "name": "Harold Wood",
        "job_title": "Manager",
        "employee_id": null,
        "created_at": "2020-02-27 14:49:30",
        "updated_at": "2020-02-27 14:49:30"
    },
    "5c0346d0-5970-11ea-b49e-816916f41cbb": {
        "id": "5c0346d0-5970-11ea-b49e-816916f41cbb",
        "name": "John Smith",
        "job_title": "Developer",
        "employee_id": "104",
        "created_at": "2020-02-27 14:49:30",
        "updated_at": "2020-02-27 14:49:30"
    },
    "5c03c180-5970-11ea-866e-f3f6da276a02": {
        "id": "5c03c180-5970-11ea-866e-f3f6da276a02",
        "name": "Paul Johnson",
        "job_title": "Engineer",
        "employee_id": "42",
        "created_at": "2020-02-27 14:49:30",
        "updated_at": "2020-02-27 14:49:30"
    },
    "5c043f80-5970-11ea-bd7e-9fc0f189b2e0": {
        "id": "5c043f80-5970-11ea-bd7e-9fc0f189b2e0",
        "name": "Mary Runton",
        "job_title": "Clerk",
        "employee_id": "78",
        "created_at": "2020-02-27 14:49:30",
        "updated_at": "2020-02-27 14:49:30"
    }
}]

As you wrote it your array only contains one object which makes its sort unefficient.当你写它时,你的数组只包含一个对象,这使得它的排序效率低下。

First you'll need to have an array containing your objects this way (as your object keys are id values I just got rid of this redundancies):首先,您需要以这种方式包含一个包含对象的数组(因为您的对象键是 id 值,我刚刚摆脱了这种冗余):

 [{
    "id": "5be471e0-5970-11ea-8e53-3dcfba064c75",
    "name": "Harold Wood",
    "job_title": "Manager",
    "employee_id": null,
    "created_at": "2020-02-27 14:49:30",
    "updated_at": "2020-02-27 14:49:30"
  },
  {
    "id": "5c0346d0-5970-11ea-b49e-816916f41cbb",
    "name": "John Smith",
    "job_title": "Developer",
    "employee_id": "104",
    "created_at": "2020-02-27 14:49:30",
    "updated_at": "2020-02-27 14:49:30"
  },
  {
    "id": "5c03c180-5970-11ea-866e-f3f6da276a02",
    "name": "Paul Johnson",
    "job_title": "Engineer",
    "employee_id": "42",
    "created_at": "2020-02-27 14:49:30",
    "updated_at": "2020-02-27 14:49:30"
  },
  {
    "id": "5c043f80-5970-11ea-bd7e-9fc0f189b2e0",
    "name": "Mary Runton",
    "job_title": "Clerk",
    "employee_id": "78",
    "created_at": "2020-02-27 14:49:30",
    "updated_at": "2020-02-27 14:49:30"
}]

Then you could simply perform an Array.sort() using a function to sort based on name value然后你可以简单地执行一个Array.sort()使用一个函数来根据name值进行排序

yourArray.sort((a, b) => {
  return a.name.localCompare(b.name);
});

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

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