簡體   English   中英

如何將 javascript 對象數組從一種格式轉換為另一種格式?

[英]How to convert a javascript array of Objects from one format to another format?

我有一個對象數組,想將它從一種格式轉換為另一種格式。

初始數組如下所示:

 const data = [ {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}}, {name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}}, {name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}} ]

如何將其轉換為這樣的格式?

 const data = [ {channel: 'Oil', 'Customer 1': 55, 'Customer 2': 59, 'Customer 3': 50}, {channel: 'Gas', 'Customer 1': 66, 'Customer 2': 96, 'Customer 3': 69}, {channel: 'Retail', 'Customer 1': 56, 'Customer 2': 86, 'Customer 3': 50}, ]

請問有什么幫助嗎?

您可以填充鍵控值類別的對象並添加相關數據。

 const data = [ {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}}, {name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}}, {name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}} ] const output = Object.values(data.reduce((a, c) => { Object.keys(c.value).forEach(k => { a[k] = a[k] || {channel: k}; a[k][c.name] = c.value[k]; }); return a; }, {})); console.log(output);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM