Collecting the keys from array of objects and reducing it into a single array and removing duplicates

DIL*_*MAS 6 javascript arrays

I am trying to extract the keys of each object in the array, then i will collect all the keys , after that i concatenate the small chunk key arrays. Then i use set to eliminate duplicates and get all the keys.

I am able to get the result. Is there any better approach for this

Any help appreciated

let data = [
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
]

let keysCollection = []

data.forEach(d => {
  let keys = Object.keys(d);
  keysCollection.push(keys)
})


let mergingKeysCollection = keysCollection.reduce((a,b) => [...a, ...b], [])

let uniqueKeys = new Set(mergingKeysCollection)

console.log('uniqueKeys', uniqueKeys)
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 4

您可以直接获取一组而不使用另一个键数组。

let data = [{ test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }],
    uniqueKeys = Array.from(
        data.reduce((r, o) => Object.keys(o).reduce((s, k) => s.add(k), r), new Set)
    );

console.log(uniqueKeys)
Run Code Online (Sandbox Code Playgroud)