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)
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%}
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.