Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficent way to get all keys in unorganized array of objects

I want to get all the keys in an array of objects. Initially I just grabbed the first object in the array and used:

var keys = Object.keys(tableData[0]);

But when I looked closer at the data I noticed that the first row didn't contain all the needed keys. In the following example the third item contains all the keys but you might have a case where getting all the keys requires combining multiple objects.

var tableData = [
  { first:"jeff", last:"doe", phone: "2891" },
  { first:"sarah", phone:"this", county: "usa" }
  { first:"bob", last:"brown", county: "usa", phone: "23211" }
];

How can I get all the unique keys in an array of objects that will be efficent at large scale?

like image 300
Philip Kirkbride Avatar asked Oct 17 '16 19:10

Philip Kirkbride


2 Answers

You could use reduce() and Set to get desired result.

var array = [
  { first:"jeff", last:"doe", phone: "2891" },
  { first:"sarah", phone:"this", county: "usa" },
  { first:"bob", last:"brown", county: "usa", phone: "23211" }
];

var keys = [...new Set(array.reduce(function(r, e) {
  r = r.concat(Object.keys(e));
  return r;
}, []))];

console.log(keys)
like image 111
Nenad Vracar Avatar answered Oct 03 '22 03:10

Nenad Vracar


You might simply do as follows;

var array = [
  { first:"jeff", last:"doe", phone: "2891" },
  { first:"sarah", phone:"this", county: "usa" },
  { first:"bob", last:"brown", county: "usa", phone: "23211" }
];

var result = array.reduce((p,o) => Object.assign(p,Object.keys(o)),[]);
console.log(result);

As per a very rightful comment here is my the next solution;

var array = [
  { first:"jeff", last:"doe", phone: "2891", moron: "me"},
  { first:"sarah", phone:"this", county: "usa" },
  { first:"bob", last:"brown", county: "usa", phone: "23211" }
];

var result = array.reduce((p,o) => p.concat(Object.keys(o).filter(k => !p.includes(k))),[]);
console.log(result);
like image 26
Redu Avatar answered Oct 03 '22 03:10

Redu