使用Lodash合并复杂对象的数组

时间:2016-09-20 22:42:23

标签: javascript arrays json underscore.js lodash

我是Lodash的新手,并试图解决这个问题,但可以找到一个好方法。

我有一个从数据库返回的对象数组。数据结构如下:

var data = [{
    index: 1,
    Aoo: "a1",
    Boo: 'b2',
}, {
    index: 1,
    Aoo: "a2",
    Boo: 'b2',
}, {
    index: 2,
    Aoo: "a3",
    Boo: 'b3',
}];

我想首先按索引对对象进行分组,然后对属性" Aoo"进行分组。和" Boo"并将其放在名为param的数组属性中。

var result = [{
        index: 1,
        param: [{
            Aoo: 'A1',
            Boo: 'B1'
        },{
            Aoo: 'A2',
            Boo: 'B2',
        }]
    }, {
        index: 2,
        param: [{
            Aoo: 'A3',
            Boo: 'B3'
        }]
   }
]

我可以手动完成,但我想充分利用Lodash的功能。现在我只知道我可以通过使用_.groupBy('index')实现分组的第一步,而我仍然坚持下一步做什么。

1 个答案:

答案 0 :(得分:5)

你快到了。以下是使用lodash

完成此操作的方法



var data = [{
    index: 1,
    Aoo: "a1",
    Boo: 'b2',
}, {
    index: 1,
    Aoo: "a2",
    Boo: 'b2',
}, {
    index: 2,
    Aoo: "a3",
    Boo: 'b3',
}];

var result = _.chain(data)
  .groupBy('index')
  .map((value, key) => {
    return {
      index: Number(key), //the index was transformed into a string, this will make it a number again.
      param: _.map(value, o => _.omit(o, 'index'))//do not include the index key from the previous objects
    }
  })
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min.js"></script>
&#13;
&#13;
&#13;

不可否认,第二部分比分组略显棘手,但不是很多。由于索引为您提供了这种结构:

&#13;
&#13;
{
  "1": [
    {
      "index": 1,
      "Aoo": "a1",
      "Boo": "b2"
    },
    {
      "index": 1,
      "Aoo": "a2",
      "Boo": "b2"
    }
  ],
  "2": [
    {
      "index": 2,
      "Aoo": "a3",
      "Boo": "b3"
    }
  ]
}
&#13;
&#13;
&#13;

你真正想做的就是重复一遍,让每个键都成为index属性,然后留下一系列初始对象。每个都需要通过删除index密钥进行转换,并将其分配给param值。这是使用.map一次完成的。不幸的是,它并不像它看起来那么漂亮,但我认为这是你用Lodash基础版本做的最好的。

如果您要选择键的特定子集,而不是&#34;除了索引&#34;之外的所有键,那么您可以使用_.pick代替{{1 }} 去做吧。这是看起来的样子:

&#13;
&#13;
_.omit
&#13;
var data = [{
    index: 1,
    Aoo: "a1",
    Boo: 'b2',
    Coo: "c1"
}, {
    index: 1,
    Aoo: "a2",
    Boo: 'b2',
    Coo: "c2"
}, {
    index: 2,
    Aoo: "a3",
    Boo: 'b3',
    Coo: "c3"
}];

var result = _.chain(data)
  .groupBy('index')
  .map((value, key) => {
    return {
      index: Number(key), //the index was transformed into a string, this will make it a number again.
      param: _.map(value, o => _.pick(o, ['Aoo', 'Boo']))//do not include the index key from the previous objects
    }
  })
  .value();

console.log(result);
&#13;
&#13;
&#13;

即使数据中有一个额外的密钥,我们也会得到相同的结果。