用lodash排序对象数组:不起作用

时间:2019-04-17 12:38:43

标签: javascript lodash

我有一个看起来像这样的数组(它有更多的对象,但是结构相同):

[
  {
      especiality: "surgery",
      users: [
          {
              id: "182",
              country: "Colombia",
              province: "Bogota",
              telephone: "211112212",
              neighbourhood: "La Santa"
              region: "South",
          },
          {
            id: "182",
            country: "Venezuela",
            province: "Caracas",
            telephone: "322323333",
            region: "North",
        },
        {
          id: "183",
          country: "Brasil",
          telephone: "23232333",
          neighbourhood: "Santos"
          region: "South",
      },
      ]
  },

如果ID相同,我希望地址组成一个单个数组(我需要映射这些元素)。外观应如下图所示:

user: [{id: 182, locations[(if they exist)               
              country: "Colombia",
              province: "Bogota",
              telephone: "211112212",
              neighbourhood: "La Santa"
              region: "South"], [country: "Venezuela",
            province: "Caracas",
            telephone: "322323333",
            region: "North"],}]

我目前正在尝试此操作,但是根本无法正常工作

getGroups = test => {
  _.chain(test)
  .groupBy("id")
  .toPairs()
  .map(item => _.zipObject(["id", "country", "province", "neighbourhood", "region"], item))
  .value();
  return test
  }

我在做什么错,我该如何解释可能并非在所有对象中都可用的值?

1 个答案:

答案 0 :(得分:1)

将项目按id分组后,映射组,并使用id创建对象,并将该组的项目命名为locations。映射位置,然后使用_.omit()从其中删除id

我不确定您要如何处理外部数组。我曾经使用_.flatMap()来获得单个用户数组,但是如果您需要维护原始结构,则有一个注释选项。

getGroups = test =>
  _(test)
  .groupBy("id")
  .map((locations, id) => ({
    id,
    locations: _.map(locations, l => _.omit(l, 'id'))
  }))
  .value();

const data = [{"especiality":"surgery","users":[{"id":"182","country":"Colombia","province":"Bogota","telephone":"211112212","neighbourhood":"La Santa","region":"South"},{"id":"182","country":"Venezuela","province":"Caracas","telephone":"322323333","region":"North"},{"id":"183","country":"Brasil","telephone":"23232333","neighbourhood":"Santos","region":"South"}]}];

const result = _.flatMap(data, ({ users }) => getGroups(users));

/** maintains the original structure
const result = _.map(data, ({ users, ...rest }) => ({
  ...rest,
  users: getGroups(users)
}));
**/

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