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']
?
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));
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With