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)
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.
We can use hashmaps to maintain the frequency of each element and then we can remove the duplicates from the array.
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)
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%}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With