Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique keys from multiple objects

Tags:

javascript

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']?

like image 358
Simon Bengtsson Avatar asked Oct 18 '25 10:10

Simon Bengtsson


2 Answers

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));
like image 95
Amit Avatar answered Oct 19 '25 23:10

Amit


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;
});
like image 39
adeneo Avatar answered Oct 19 '25 22:10

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!