It's All Writing.

Writing makes you happy.

How to implement multiple key's group by at node

Prerequisites

There are arrays has multiple elements as below.

[
  {
    "name": "SHINCHI, Takahiro",
    "mail": "shinchi@its-all-writing.com",
    "hobby": "Walking"
  },
  {
    "name": "SHINCHI, Takahiro",
    "mail": "shinchi.xx@gmail.com",
    "hobby": "Playing the Bamboo Flute"
  },
  {
    "name": "SHINCHI, Kazuyo",
    "mail": "kazuyo@its-all-writing.com",
    "hobby": "Reading Books",
  },
  {
    "name": "SHINCHI, Kazuyo",
    "mail": "kazuyo@its-all-writing.com",
    "hobby": "Driving",
  }
]

Then, we want to convert this array to be as below.

{
  "SHINCHI, Takahiro": {
    "shinchi@its-all-writing.com": [
      {
        "name": "SHINCHI, Takahiro",
        "mail": "shinchi@its-all-writing.com",
        "hobby": "Walking"
      }
    ],
    "shinchi.xx@gmail.com": [
      {
        "name": "SHINCHI, Takahiro",
        "mail": "shinchi.xx@gmail.com",
        "hobby": "Playing the Bamboo Flute"
      }
    ]
  },
  "SHINCHI, Kazuyo": {
    "kazuyo@its-all-writing.com": [
      {
        "name": "SHINCHI, Kazuyo",
        "mail": "kazuyo@its-all-writing.com",
        "hobby": "Reading Books"
      },
      {
        "name": "SHINCHI, Kazuyo",
        "mail": "kazuyo@its-all-writing.com",
        "hobby": "Driving"
      }
    ]
  }
}

Environment

  • node
  • lodash

Code

const lodash = require('lodash');

let data = [
  {
    "name": "SHINCHI, Takahiro",
    "mail": "shinchi@its-all-writing.com",
    "hobby": "Walking"
  },
  {
    "name": "SHINCHI, Takahiro",
    "mail": "shinchi.xx@gmail.com",
    "hobby": "Playing the Bamboo Flute"
  },
  {
    "name": "SHINCHI, Kazuyo",
    "mail": "kazuyo@its-all-writing.com",
    "hobby": "Reading Books",
  },
  {
    "name": "SHINCHI, Kazuyo",
    "mail": "kazuyo@its-all-writing.com",
    "hobby": "Driving",
  }
];

data = lodash.groupBy(data, function(item) {
  return item.name;
});
lodash.forEach(data, function(value, key) {
 data[key] = lodash.groupBy(data[key], function(item) {
    return item.mail;
  });
});