简体   繁体   English

如何将表格行数据转换为 javascript 中的列数据

[英]How can I convert tabular row data to column data in javascript

so I need to convert an array that contains tabular row data into column data in a specific format so I can use it to display a chart with Recharts.所以我需要将包含表格行数据的数组转换为特定格式的列数据,以便我可以使用它来显示带有 Recharts 的图表。

My data is in the following format:我的数据格式如下:

rows = [
    ['Year', '2010', '2011', '2012', '2013'], 
    ['wages','2000','2000','2050','2050'], 
    ['purchase cost', '4000', '4300', '4500', '5000']
]

I need the data to be formatted as follows:我需要将数据格式化如下:

columns = [
    {'Year' : '2010', 'wages' : '2000', 'purchase cost' : '4000'}, 
    {'Year' : '2011', 'wages' : '2000', 'purchase cost' : '4300'}, 
    {'Year' : '2012', 'wages' : '2050', 'purchase cost' : '4500'}, 
    {'Year' : '2013', 'wages' : '2050', 'purchase cost' : '5000'}
]

I've gotten close to getting the result I need but can't seem to get it to work, so I would appreciate any help with this!我已经接近获得所需的结果,但似乎无法使其正常工作,因此我将不胜感激!

Keep two principles坚持两个原则

  1. The subarrays are all the same length.子数组的长度都相同。
  2. The first element of the subarray is the column name.子数组的第一个元素是列名。

I implemented it in several steps, you can refer to the following code.我分几步实现的,你可以参考下面的代码。

 const rows = [ ['Year', '2010', '2011', '2012', '2013'], ['wages', '2000', '2000', '2050', '2050'], ['purchase cost', '4000', '4300', '4500', '5000'] ]; const property = rows.map(row => row[0]); const columns = rows.map(row => { row.shift(); return row }); const data = columns.map((column, i) => { return column.map(col => { const obj = {}; obj[property[i]] = col; return obj; }); }); const result = new Array(columns[0].length); for (let i = 0; i < result.length; i++) { const obj = {}; for (let j = 0; j < property.length; j++) { for (const [key, value] of Object.entries(data[j][i])) { obj[key] = value; } } result[i] = obj; } console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM