我试图提取数组中每个对象的键,然后收集所有键,然后将小块键数组连接起来。然后我使用set消除重复项并获取所有密钥。
我能够得到结果。有没有更好的方法
任何帮助表示赞赏
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)
答案 0 :(得分:4)
您可以直接使用一组而不使用另一个键阵列。
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)
答案 1 :(得分:2)
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 {
max-height: 100% !important;
top: 0;
}