Categories
JavaScript Answers

How to add keys for grouped output with lodash .groupBy and JavaScript?

Spread the love

Sometimes, we want to add keys for grouped output with lodash .groupBy and JavaScript.

In this article, we’ll look at how to add keys for grouped output with lodash .groupBy and JavaScript.

How to add keys for grouped output with lodash .groupBy and JavaScript?

To add keys for grouped output with lodash .groupBy and JavaScript, we can use the map method to add the keys returned by the groupby method.

For instance, we write

const data = [
  {
    name: "jim",
    color: "blue",
    age: "22",
  },
  {
    name: "non",
    color: "blue",
    age: "33",
  },
  {
    name: "joey",
    color: "green",
    age: "77",
  },
];

console.log(
  _.chain(data)
    .groupBy("color")
    .map((value, key) => ({ color: key, users: value }))
    .value()
);

to call chain with data and groupBy to return an array of data items grouped by the color property value.

And then we call map with a callback that sets the color to the key color value and users is set to value which has the data with the given color key value.

And then we call value to return the values.

Conclusion

To add keys for grouped output with lodash .groupBy and JavaScript, we can use the map method to add the keys returned by the groupby method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *