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?
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With