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.
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);
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]))
Using Array.flatMap and a Set object to get a Set of unique keys and then use the spread operator to convert the Set back into an array.
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 res = [...new Set(all.flatMap(Object.keys))];
console.log(res);