使用filter,groupby和orderby映射json数组的值

时间:2019-02-26 21:10:21

标签: angular ecmascript-6 lodash

我的json格式如下

[{
    "id": 1,
    "role": {
      "id": "25",
    },
    "target": {
      "id": "1083",
    },
    "staff": {
      "name: "
      ccc "
    }
  },
  {
    "id": 2,
    "role": {
      "id": "25",
    },
    "target": {
      "id": "1083",
    },
    "staff": {
      "name: "
      aaa "
    }
  },
  {
    "id": 3,
    "role": {
      "id": "25",
    },
    "target": {
      "id": "1084",
    },
    "staff": {
      "name: "
      staff1 "
    }
  },
  {
    "id": 4,
    "role": {
      "id": "3",
    },
    "target": {
      "id": "1083",
    },
    "staff": {
      "name: "
      aaa "
    }
  }
]

我正在尝试按角色ID对所有特定目标ID进行分组。一切正常,除了我还希望按人员姓名对内容进行排序。

const groupIt = targetId =>
  chain(data[2])
  .filter(x => x.target.id === targetId)
  .groupBy("role.id")
  .value()

console.log(groupIt('1083'))

预期结果

{
  "25": [{
      "id": 2 "role": {
        "id": "25",
      },
      "target": {
        "id": "1083",
      },
      "staff": {
        "name": "aaa"
      }

    },
    {
      "id": 2 "role": {
        "id": "25",
      },
      "target": {
        "id": "1083",
      },
      "staff": {
        "name": "ccc"
      }
    }
  ],
  "3": [{
    "id": 4,
    "role": {
      "id": "3",
    },
    "target": {
      "id": "1083",
    },
    "staff": {
      "name": "staff1"
    }
  }]
}

我也尝试同时保持orderBy,但是没有用。我正在考虑遍历每个角色并对其进行排序。但是我在想是否还有其他解决方案。

1 个答案:

答案 0 :(得分:0)

您可以先订购然后对物品进行分组。这将在组内设置顺序。但是,由于role.idnumeric property that can be converted to an integer,因此不会影响组的顺序。

const data = [{"id":1,"role":{"id":"25"},"target":{"id":"1083"},"staff":{"name":"ccc"}},{"id":2,"role":{"id":"25"},"target":{"id":"1083"},"staff":{"name":"aaa"}},{"id":3,"role":{"id":"25"},"target":{"id":"1084"},"staff":{"name":"staff1"}},{"id":4,"role":{"id":"3"},"target":{"id":"1083"},"staff":{"name":"aaa"}}]

const groupIt = targetId =>
  _(data)
  .filter(['target.id', targetId])
  .orderBy('staff.name')
  .groupBy('role.id')
  .value()

console.log(groupIt('1083'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>