Efficent way to get all keys in unorganized array of objects
arrays, javascript, json, sorting
Solution
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)
Problem
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?