我想获取对象数组中的所有键。最初我只是抓住了数组中的第一个对象并使用了:
var keys = Object.keys(tableData[0]);
但是当我仔细观察数据时,我注意到第一行没有包含所有需要的键。在下面的示例中,第三个项目包含所有键,但您可能遇到了获取所有键需要组合多个对象的情况。
var tableData = [
{ first:"jeff", last:"doe", phone: "2891" },
{ first:"sarah", phone:"this", county: "usa" }
{ first:"bob", last:"brown", county: "usa", phone: "23211" }
];
如何获得大规模高效的对象数组中的所有唯一键?
答案 0 :(得分:5)
var array = [
{ first:"jeff", last:"doe", phone: "2891" },
{ first:"sarah", phone:"this", county: "usa" },
{ first:"bob", last:"brown", county: "usa", phone: "23211" }
];
var keys = [...new Set(array.reduce(function(r, e) {
r = r.concat(Object.keys(e));
return r;
}, []))];
console.log(keys)
答案 1 :(得分:3)
您可以按照以下步骤进行操作;
var array = [
{ first:"jeff", last:"doe", phone: "2891" },
{ first:"sarah", phone:"this", county: "usa" },
{ first:"bob", last:"brown", county: "usa", phone: "23211" }
];
var result = array.reduce((p,o) => Object.assign(p,Object.keys(o)),[]);
console.log(result);
根据一个非常合理的评论,这是我的下一个解决方案;
var array = [
{ first:"jeff", last:"doe", phone: "2891", moron: "me"},
{ first:"sarah", phone:"this", county: "usa" },
{ first:"bob", last:"brown", county: "usa", phone: "23211" }
];
var result = array.reduce((p,o) => p.concat(Object.keys(o).filter(k => !p.includes(k))),[]);
console.log(result);

答案 2 :(得分:2)
var arr = [
{ first:"jeff", last:"doe", phone: "2891", something: "4" },
{ first:"sarah", phone:"this", county: "usa" },
{ first:"bob", last:"brown", county: "usa", phone: "23211", lastrow: "lr" }
];
var set = new Set();
arr.map(obj => {
Object.keys(obj).forEach(el => {
set.add(el);
});
});
var res = [...set];
console.log(res);

我已使用@Nenad Vracar和@Redu中的代码测试了上述代码中Chrome浏览器中的console time
:
var array = [
{ first:"jeff", last:"doe", phone: "2891", something: "4" },
{ first:"sarah", phone:"this", county: "usa" },
{ first:"bob", last:"brown", county: "usa", phone: "23211", lastrow: "lr" }
];
function f1(arr) { // Peter Leger
var set = new Set();
arr.map(obj => {
Object.keys(obj).forEach(el => {
set.add(el);
});
});
var res = [...set];
return res;
}
function f2(arr) { // Nenad Vracar
var keys = [...new Set(arr.reduce(function(r, e) {
r = r.concat(Object.keys(e));
return r;
}, []))];
return keys;
}
function f3(arr) { // Redu
var result = arr.reduce((p,o) => p.concat(Object.keys(o).filter(k => !p.includes(k))),[]);
return result;
}
var iterations = 1000000;
console.time('Function f1');
for(var i = 0; i < iterations; i++ ){
f1(array);
};
console.timeEnd('Function f1')
console.time('Function f2');
for(var i = 0; i < iterations; i++ ){
f2(array);
};
console.timeEnd('Function f2')
console.time('Function f3');
for(var i = 0; i < iterations; i++ ){
f3(array);
};
console.timeEnd('Function f3')
具有以下结果:
第一个结果:
第二个结果:
第三个结果: