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)
您可以直接获取一组而不使用另一个键数组。
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)
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |