我想从数组对象中提取字段名称,称为
results
,在 Javascript 中具有以下结构
Object { data: (5) […] }
data: Array(5) [ {…}, {…}, {…}, … ]
0: Object { nClients: 4 }
1: Object { name: "test1", roll_no: 321, branch: "it" }
2: Object { name: "test2", roll_no: 321, branch: "it" }
3: Object { name: "test3", roll_no: 321, branch: "it" }
4: Object { name: "test4", roll_no: 321, branch: "it", … }
length: 5
<prototype>: Array []
<prototype>: Object { … }
我想提取一个字段列表,例如
[nClients, name, roll_no, branch]
。有什么建议吗?
谢谢!
您可以使用
Array#reduce
和 Object.keys()
来收集集合中的道具名称:
const arr = [
{ nClients: 4 },
{ name: "test1", roll_no: 321, branch: "it" },
{ name: "test2", roll_no: 321, branch: "it" },
{ name: "test3", roll_no: 321, branch: "it" },
{ name: "test4", roll_no: 321, branch: "it" , prop1: true},
];
const fields = [...arr.reduce((r, i) => (Object.keys(i).forEach(k => r.add(k)), r), new Set)];
console.log(...fields);