首页 > 解决方案 > 如何对具有多组json对象的json数组进行排序

问题描述

我想根据 name 属性对下面的 json 数组进行排序。挑战是如果“行”包含两个 json 数组元素,那么它应该首先在组内做空,然后根据另一个 json 数组进行排序。

这是我的尝试。它正在对数组进行排序,而不是对(组内的元素)进行排序

// sort the data
this.leadPoolRecords = JSON.parse(
  JSON.stringify(this.leadPoolRecords)
).sort((a, b) => {
  a = a[colName] ? a[colName].toLowerCase() : ""; // Handle null values
  b = b[colName] ? b[colName].toLowerCase() : "";
  return a > b ? 1 * isReverse : -1 * isReverse;
});

data =    [
      {
        "button": {
          "btn": true,
          "size": "20"
        },
        "rows": [
          {
            "name": "john",
            "role": "CEO",
            "phone": "xxxxxxxxx",
            "email": "bcd@email.com"
          }
        ]
      },
      {
        "button": {
          "btn": true,
          "size": "20"
        },
        "rows": [
          {
            "name": "Mike",
            "role": "Director",
            "phone": "xxxxxxxxx",
            "email": "cde@email.com"
          }
        ]
      },
      {
        "button": {
          "btn": true,
          "size": "20"
        },
        "rows": [
          {
            "name": "rahul",
            "role": "CTO",
            "phone": "xxxxxxxxx",
            "email": "xyz@email.com"
          },
          {
            "name": "ajay",
            "role": "Researcher",
            "phone": "xxxxxxxxx",
            "email": "abc@email.com"
          }
        ]
      }
    ]

标签: javascriptarraysjsonsorting

解决方案


首先,您可以rows这样对数组进行排序:

data.forEach(item => item.rows.sort((row1, row2) => row1.name.localeCompare(row2.name)));

data然后您可以根据rows数组对元素进行排序。例如,如果要根据name第一行的 对它们进行排序:

data.sort((item1, item2) => item1.rows[0].name.localeCompare(item2.rows[0].name));

推荐阅读