【问题标题】:Mapping the value of a json array using filter, groupby and orderby使用 filter、groupby 和 orderby 映射 json 数组的值
【发布时间】:2019-07-20 12:09:58
【问题描述】:

我有以下格式的 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 ,但没有奏效。我正在考虑遍历每个角色并对它们进行排序。但我正在考虑是否有其他解决方案。

【问题讨论】:

    标签: angular ecmascript-6 lodash


    【解决方案1】:

    您可以 orderBy 然后对项目进行分组。这将设置组内的顺序。但是,它不会影响组的顺序,因为 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>

    【讨论】:

    • Droi 谢谢。有没有一种方法可以让我通过不区分大小写的人员进行排序。
    • 可以使用函数返回staff.name.toLowerCase()
    • Droi 我没有完全理解。是不是一定要使用上述逻辑中的函数?
    • .orderBy(o => o.staff.name.toLowerCase())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多