Get key union of all objects in js array using shorthand

Let's pretend that:

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

Expected Result ['firstname','age', 'children', 'fullname']: The union of the keys of all objects in this array:

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

It works well. However, I am looking for a higher performance solution using the method reducedirectly without map, I did the following, and it failed.

all.reduce((a,b) =>Object.assign([...Object.keys(a),...Object.keys(b)]),[])
+4
source share
4 answers

You can use Set, reduce()and Object.keys(), there is no need for a 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)
Run codeHide result
+3
source

concat, flatMap ES6 Set.

@NenadVracar, do-it-all-in-one-line. .

, ... , , .

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

const concat = (x,y) => x.concat(y);

const flatMap = f => xs => xs.map(f).reduce(concat, []);

const unionKeys = xs =>
  Array.from(new Set(flatMap (Object.keys) (xs)));

console.log(unionKeys(all));
// [ 'firstname', 'age', 'children', 'fullname' ]
Hide result
+1

:

var union = new Set(getKeys(all));

console.log(union);
// if you need it to be array
console.log(Array.from(union));

//returns the keys of the objects inside the collection
function getKeys(collection) {
    return collection.reduce(
        function(union, current) {
            if(!(union instanceof Array)) {
                union = Object.keys(union);
            }
            return union.concat(Object.keys(current));
        });
}
0

, ( vs foreach vs set). , Set , ( foreach).

, .

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

const concat = (x,y) => x.concat(y);

const flatMap = f => xs => xs.map(f).reduce(concat, []);

const unionKeys = xs =>
  Array.from(new Set(flatMap (Object.keys) (xs)));

for(var i = 0; i < 10; i++)
  all = all.concat(all);

console.time("Reduce");
result = Object.keys(all.reduce((memo, obj) => Object.assign(memo, obj), {}));
console.timeEnd("Reduce");

console.time("foreach");
all.forEach(obj => Object.assign(res, obj));
result = Object.keys(res);
console.timeEnd("foreach");

console.time("Set");
result = [...new Set(all.reduce((r, e) => r.concat(Object.keys(e)), []))];
console.timeEnd("Set");

console.time("Set2");
result = unionKeys(all);
console.timeEnd("Set2");
Hide result
0

Source: https://habr.com/ru/post/1658492/


All Articles