Open In App

How to Create Collection from Duplicate Object Keys in Lodash?

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes we come across situations where you have objects with duplicate keys and you need to create a collection from these keys. we will create a Collection from Duplicate Object Keys using the functions of the Lodash.

Below are different approaches that we can use to create a collection from duplicate object keys in Lodash:

Using _.groupBy() Method

The _.groupBy() method creates an object composed of keys generated from the results of running each element of the collection through the iteratee function. Each key is associated with an array of elements for which the key is returned.

Syntax:

_.groupBy(collection, iteratee);

Example: The code groups the people array by the name property using Lodash's _.groupBy method, resulting in an object where each key is a name and each value is an array of objects with that name.

JavaScript
const _ = require('lodash');

let people = [
    { name: 'geek', age: 25 },
    { name: 'geekina', age: 30 },
    { name: 'geek', age: 40 }
];

let grouped = _.groupBy(people, 'name');

console.log(grouped);

Output:


{
geek: [ { name: 'geek', age: 25 }, { name: 'geek', age: 40 } ],
geekina: [ { name: 'geekina', age: 30 } ]
}

Using _.countBy() Method

The _.countBy() method counts the occurrences of elements in a collection based on a criterion and returns an object with counts.

Syntax:

_.countBy(collection, iteratee);

Example: The code counts the occurrences of each unique key in the `items` array using Lodash's _.countBy method and outputs the result as an object.

JavaScript
const _ = require('lodash');

let items = [
    { key: 'x', value: 10 },
    { key: 'y', value: 20 },
    { key: 'x', value: 30 }
];

let counts = _.countBy(items, 'key');

console.log(counts);

Output:

{
"x": 2,
"y": 1
}

Next Article

Similar Reads