Get all unique object properties from array of objects
You can use Object.assign()
and spread syntax to merge the array of objects to a single object. Then get the keys from the merged object:
Object.keys(Object.assign({}, ...array))
Here's a snippet:
const array = [{firstName:"John",lastName:"Doe"},{firstName:"Anna",car:true},{firstName:"Peter",lastName:"Jones"}],
unique = Object.keys(Object.assign({}, ...array))
console.log(unique)
Another option is to use Object.keys
as callback to flatMap
. This returns an array of all the keys. Then, create a Set
to get unique keys and use Array.from()
to convert the set to an array.
const keys = input.flatMap(Object.keys),
unique = Array.from(new Set(keys));
Here's a working snippet:
const input=[{firstName:"John",lastName:"Doe"},{firstName:"Anna",car:true},{firstName:"Peter",lastName:"Jones"}],
unique = Array.from(new Set(input.flatMap(Object.keys)));
console.log(unique)
If flatMap
is not supported, you can use
const keys = [].concat(...input.map(Object.keys)),
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>
A solution using only:
Object.assign
Object.keys
Array.prototype.reduce
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);