Home > Enterprise >  JS getting union of all object keys from an array of objects
JS getting union of all object keys from an array of objects

Time:10-14

I have below array of objects:

var all = [
{f1: "v1", f2: "v2"},
{f1: "v1", f2: "v2", f3: "v3"},
{f1: "v1", f2: "v2", f3: "v3", f4: "v4"},
{f1: "v1", f2: "v2", f3: "v3", f4: "v4", fn: "vn"}
];

Desired Output:

[f1, f2, f3, f4, f5, ...., fn];

Currently Using:

all.reduce((sum, item) => ([...new Set([...sum, ...Object.keys(item)])]), []);

Working Example: codepen

Any suggestions using es6 or any new js feature, for better performance.

CodePudding user response:

You can flatten them into a single object, then take the keys.

var all = [
{f1: "v1", f2: "v2"},
{f1: "v1", f2: "v2", f3: "v3"},
{f1: "v1", f2: "v2", f3: "v3", f4: "v4"},
{f1: "v1", f2: "v2", f3: "v3", f4: "v4", fn: "vn"}
];

const output = Object.keys(Object.assign({}, ...all));
console.log(output);

CodePudding user response:

var all = [
{f1: "v1", f2: "v2"},
{f1: "v1", f2: "v2", f3: "v3"},
{f1: "v1", f2: "v2", f3: "v3", f4: "v4"},
{f1: "v1", f2: "v2", f3: "v3", f4: "v4", fn: "vn"}
];

console.log(Object.keys(all[all.length-1]))
  • Related