How to get all the unique properties from a group of objects in JavaScript

How to get all the unique properties from a group of objects in JavaScript

In this tutorial, we’ll look at how to get all the unique properties from a group of objects.

Say you had the following objects:

const user = {
    name: 'James',
    role: 'Developer',
    age: 37,
};

const manager = {
    name: 'Hamza',
    type: 'IT',
    permissions: 'Admin',
};

const supervisor = {
    name: 'Sarah',
    age: 24,
    department: 'HR',
};

You might want to get all of the properties that are present in the group of objects and then reduce that to the unique items only.

Here’s one way you could do that.

First, let’s find a list of all the properties in the group of objects.

const allProperties = [user, manager, supervisor]
    .reduce((acc, item) => ([...acc, ...Object.keys(item)]), []));
// ["name", "role", "age", "name", "type", "permissions", "name", "age", "department"]

To do this, I’ve put all of the objects into an array and called the reduce function and then reduced the original array to another array but this time, spreading the result of Object.keys to an array.

An alternative would be to use a map and flat approach:

const allProperties = [user, manager, supervisor].map(item => ([...Object.keys(item)])).flat();

Either way, once we have a list of all the properties, we can get just the unique ones by creating a new Set object. (If we want to return these unique values in an array we can spread them back into an array.)

const uniqueProperties = [...new Set(allProperties)];
// ["name", "role", "age", "type", "permissions", "department"]

There are most likely a few other ways to go about this but in essence, you’ll want to be using Object.keys to get a list of each object’s properties and then go about combining them all together before passing the list to a Set or some other way of removing the duplicate items.

Follow me on Twitter for more tutorials 👍