Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all unique object properties from array of objects

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?

like image 914
Andurit Avatar asked Aug 31 '16 11:08

Andurit


People also ask

Which object lets you store unique values of any type?

The Set object lets you store unique values of any type, whether primitive values or object references.


2 Answers

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>
like image 38
Nenad Vracar Avatar answered Oct 10 '22 22:10

Nenad Vracar


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);
like image 123
user3297291 Avatar answered Oct 10 '22 22:10

user3297291