Abdennour TOUMI Abdennour TOUMI - 1 month ago 9
Javascript Question

Get union of keys of all objects in js array using reduce

Assume , we have :

var all=[
{firstname:'Ahmed', age:12},
{firstname:'Saleh', children:5 }
{fullname: 'Xod BOD', children: 1}
];


The expected result is
['firstname','age', 'children', 'fullname']
: the union of keys of all objects of that array:

all.map((e) => Object.keys(e) ).reduce((a,b)=>[...a,...b],[]);


This is work fine , However, i am seeking a solution more performance using directly
reduce
method without
map
, I did the following and it is failed.

all.reduce((a,b) =>Object.assign([...Object.keys(a),...Object.keys(b)]),[])

Answer

You can use Set, reduce() and Object.keys() there is no need for map.

var all=[
  {firstname:'Ahmed', age:12},
  {firstname:'Saleh', children:5 },
  {fullname: 'Xod BOD', children: 1}
];

var result = [...new Set(all.reduce((r, e) => [...r, ...Object.keys(e)], []))];
console.log(result)