Search code examples
javascriptjavascript-objects

Extract Unique Keys from an array of Objects


I have an array of objects which looks like this:

[  
   {  
      "a":"alpha",
      "b":{  
         "x":true,
         "y":true
      }
   },
   {  
      "a":"beta",
      "b":{  
         "x":true,
         "z":true
      }
   }
]

I want to loop through this array to get a qnique list of all keys of 'b' alone. So, that my resulting array will be:

[x,y,z]

I tried the following:

const mykeys = myArray.map(item => Object.keys(item.b))

However, this only gves me: [[x,y], [y,z]]

How can I get the result as [x,y,z] instead.


Solution

  • Use Array#reduce to concatenate the arrays into single array. Then using spread operator with Set you can get unique items.

    Set lets you to store unique values.

    const myArray = [  
       {  
          "a":"alpha",
          "b":{  
             "x":true,
             "y":true
          }
       },
       {  
          "a":"beta",
          "b":{  
             "x":true,
             "z":true
          }
       }
    ]
    
    const mykeys = myArray.map(item => Object.keys(item.b))
                          .reduce((a,b) => a.concat(b));
                          
    const uniqueKeys = [...new Set(mykeys)];
    
    console.log(uniqueKeys);