Let's imagine I have an array of objects e.g.
[{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"car": true
}, {
"firstName": "Peter",
"lastName": "Jones"
}]
I want to get all the unique property names from this array of objects, so the result will be:
[firstName, lastName, car]
How can I do it:
I can imagine that it's possible to do this with something like this:
function getPropertiesNames(obj){
var arr = [];
for(var name in obj) {
if(arr.indexOf(name) != -1) arr.push(name);
}
return arr;
}
Why I need it:
I will have to make a table of multiple objects. Because each object can be a bit different I need unique property names. However I am going to do it in angularJS so it's kind of a bad option for me to once use loop to get property names for <th>
and once again use loop with <tr ng-repeat></tr>
to display values.
What i want:
Is there some option to get all unique property names from an array of objects without iterating it? Maybe some lodash or build in JS function which I don't know?
The Set object lets you store unique values of any type, whether primitive values or object references.
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);
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