繁体   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