Get all unique object properties from array of objects
A solution using only:
var data = [{ "firstName": "John", "lastName": "Doe"}, { "firstName": "Anna", "car": true}, { "firstName": "Peter", "lastName": "Jones"}];var uniqueKeys = Object.keys(data.reduce(function(result, obj) { return Object.assign(result, obj);}, {}))console.log(uniqueKeys);
You could use map()
and keys()
to return keys of each object and then union()
and flatten()
var data = [{ "firstName": "John", "lastName": "Doe"}, { "firstName": "Anna", "car": true}, { "firstName": "Peter", "lastName": "Jones"}]var result = _.union(_.flatten(_.map(data, (e) => _.keys(e))));console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
I don't think you can get away from checking each key in each object. You could accomplish it with e.g reduce:
var result = _.reduce(array, function(memory, obj) { for (var key in obj) { if(memory.indexOf(key) === -1) memory.push(key) } return memory;}, []);
Alternatively, you could store the keys in a new object, and just extract the keys:
var temp = _.reduce(array, function(memory, obj) { for (var key in obj) { memory[key] = null; } return memory;}, {});var result = Object.keys(temp);