Philip Kirkbride Philip Kirkbride - 1 month ago 5
JSON Question

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 array = [
{ 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?

Answer

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)

Comments