Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 737
Learner Avatar asked May 23 '19 12:05

Learner


People also ask

How do you remove duplicates from array of objects?

Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.

Which of the following can be used to remove duplicate entry in the array?

We can use hashmaps to maintain the frequency of each element and then we can remove the duplicates from the array.


2 Answers

You could take directly a set without using another array of keys.

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)
like image 190
Nina Scholz Avatar answered Sep 18 '22 17:09

Nina Scholz


const 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"},];

const res = data.reduce((unique, item) => (Object.keys(item).forEach(key => unique.add(key)), unique), new Set);

console.log([...res]);
.as-console-wrapper {min-height: 100%}
like image 30
Yevgen Gorbunkov Avatar answered Sep 21 '22 17:09

Yevgen Gorbunkov