Merge array of complex objects by using Lodash

前端 未结 1 647
天命终不由人
天命终不由人 2021-01-15 15:07

I\'m new to Lodash and trying to solve this problem but could find a good way to do it.

I have an array of objects return back from the database. The data is struc

1条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 15:51

    You are almost there. Here is how this can be done using 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);

    The second part is, admittedly, slightly trickier than the grouping, but not by much. Since indexing gives you this structure:

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

    All you really want to do is go over it, make each key be the index property and then you are left with an array of the inital objects. Each needs to be transformed by removing the index key and that will be assigned to the param value. This is done in one go using .map. Unfortunately, it's not as pretty as it could look but I think that's the best you can do with the base version of Lodash.

    If you want to select a specific subset of the keys, instead of "all but index", then you can use _.pick instead of _.omit to do it. Here is how this would look:

    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);

    So we get the same result even though there is an extra key in the data.

    0 讨论(0)
提交回复
热议问题