我有一个代码可以生成像这样的数组对象
[{
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 43323,
}, {
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 213,
"part@18%": 140.04,
"part@12%": 140.04,
"part@9%": 140.04,
"labour@18%": 140.04,
"offer@12%": 140.04,
"offer@9%": 140.04,
}, {
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 213,
},
{
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 213,
"part@9%": 140.04,
"labour@18%": 140.04,
"offer@12%": 140.04,
}
]
part @,labour @和offer @键是动态的。我想要数组对象中的所有键。 我想要的结果是
[ '发票号码', '发票日期', 'jobCardNumber', '税', 'part @ 18%', “ part @ 12%”, “ part @ 9%”, '人工@ 18%', “ offer @ 12%”, “优惠@ 9%” ]
答案 0 :(得分:1)
您可以使用Array.prototype.reduce
遍历对象并将其键添加到Set
:
var data=[{invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:43323},{invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:213,"part@18%":140.04,"part@12%":140.04,"part@9%":140.04,"labour@18%":140.04,"offer@12%":140.04,"offer@9%":140.04},{invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:213},{invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:213,"part@9%":140.04,"labour@18%":140.04,"offer@12%":140.04}];
var result = [...data.reduce((all, el) => (Object.keys(el).forEach(k => all.add(k)),all), new Set)];
console.log(result);