Simon Bengtsson
Simon Bengtsson

Reputation: 8151

Get unique keys from multiple objects

If I have an array of objects like this:

var mountains = [
    { name: 'Kebnekaise', elevation: 2106 },
    { name: 'Mount Ngauruhoe', elevation: 2291, comment: 'aka Mount Doom' }
];

How to get all unique keys i.e. ['name', 'elevation', 'comment']?

Upvotes: 4

Views: 4726

Answers (3)

Amit
Amit

Reputation: 46323

In ECMAScript 2015, it's really simple:

let mountains = [
  { name: 'Kebnekaise', elevation: 2106 },
  { name: 'Mount Ngauruhoe', elevation: 2291, comment: 'aka Mount Doom' }
];

let uniqueKeys = Object.keys(Object.assign({}, ...mountains));

Upvotes: 11

Shannon Scott Schupbach
Shannon Scott Schupbach

Reputation: 1278

You could iterate over the array of objects and iterate over each element's keys with Object.keys(obj), adding them to a hash to avoid duplicates:

function getKeySet (data) {
  var keys = {};

  data.forEach(function (datum) {
    Object.keys(datum).forEach(function (key) {
      keys[key] = true;
    });
  });

  return Object.keys(keys);
}

Alternately you could add all the keys to an array and filter out duplicates. Either way this will be O(nm) where n is the number of elements in the array and m is the average number of keys.

Upvotes: 1

adeneo
adeneo

Reputation: 318222

Using ES6, one could do

var unique = new Set([].concat.apply([],mountains.map(Object.keys)))

Without ES6, something like

var unique = [].concat.apply([],mountains.map(Object.keys)).filter(function(value,i,arr) {
    return arr.indexOf(value) === i;
});

Upvotes: 2

Related Questions