Search code examples
javascriptangularjsarraysobjectlodash

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?


Solution

  • 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);