简体   繁体   English

从对象数组中收集键并将其缩小为单个数组并删除重复项

[英]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. 然后我使用set来消除重复并获取所有密钥。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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