Search code examples
javascriptarraysjavascript-objects

Find number of distinct Keys in an unstructured array of objects


I need to find the number of distinct keys that exist in an array of objects in an unstructured dataset for eg

[{"a":10, b:"20"}, {"a":90, "b":30}, {"b":40, "c":79}, {"b":58, "d":50}]

the use case is to find the distinct keys ie [a, b, c, d]

The particular use case can be solved using a loop but is there a smarter way of doing that?


Solution

  • Spread the array into Object.assign() to combine all objects to a single object, and then get the keys with Object.keys():

    const data = [{"a":10, b:"20"}, {"a":90, "b":30}, {"b":40, "c":79}, {"b":58, "d":50}]
    
    const keys = Object.keys(Object.assign({}, ...data));
    
    console.log(keys); // keys
    console.log(keys.length); // number of keys