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 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 in to 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 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 in to an array.)

const uniqueProperties = [ 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.