Finding all the keys in the array of objects

Viewed 165

Given that I have an array that is return from database that contains object,

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4, c: 66}, 
   {a: 5, b: 6, c: 55, d: 66}, 
   {a: 7, b: 8, c: 12, e: 15}
];

How can I get all the keys of the object? I've been using this to obtain the keys, however I notice that index 0 wont always have all the keys. Hence problem lays.

let columns = Object.keys(jsObjects[0]),

However, the first index won't always have all the columns.

My desired output:

["a", "b", "c", "d", "e"]
4 Answers

Sets are good at removing duplicates:

const jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4, c: 66}, 
   {a: 5, b: 6, c: 55, d: 66}, 
   {a: 7, b: 8, c: 12, e: 15}
];

const keys = [...new Set(jsObjects.flatMap(Object.keys))];
console.log(keys);

You could create an object with the count of the keys and get the keys from counts.

const
    objects = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 66 }, { a: 5, b: 6, c: 55, d: 66 }, { a: 7, b: 8, c: 12, e: 15 }],
    result = Object.keys(objects.reduce((r, o) => {
        Object.keys(o).forEach(k => r[k] = true);
        return r;
    }));

console.log(result);

You can use a Set(), which is like an array with the exception that it doesn't allow multiple occurances of elements.

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4, c: 66}, 
   {a: 5, b: 6, c: 55, d: 66}, 
   {a: 7, b: 8, c: 12, e: 15}
];

var keys = new Set();
for(object of jsObjects) {
  for(key in object) {
    keys = keys.add(key);
  }
}

for (const key of keys) {
  console.log(key);
}

I tried this solution: iterating on jsObjects elements and pushing keys into columns array if not present.

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4, c: 66}, 
   {a: 5, b: 6, c: 55, d: 66}, 
   {a: 7, b: 8, c: 12, e: 15}
];
let columns = [];
jsObjects.forEach(
    o => {
        Object.keys(o).forEach(
            t => {
                if (columns.indexOf(t) < 0 ) {
                    columns.push(t);
                }
            }
        )
    }
)    
console.log(columns);

Related