简体   繁体   中英

JS getting union of all object keys from an array of objects

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM