保存转置 JSON 到 excel sheet

save a transpose JSON to excel sheet

我正在尝试转置 JSON 并将其保存到 excel sheet:

function transpose(a) {
    return Object.keys(a[0]).map(function(c) {
        return a.map(function(r) { return r[c]; });
    });
}

//example for JSON (in the program I get a long JSON in this shape)
const sheet_arr = [{'param1': 1, 'param2': 2},{'param1': 3, 'param2': 4},{'param1': 5, 'param2': 6}] 
 
var temp_ws = xls.utils.json_to_sheet(transpose(sheet_arr));
wb.Sheets['test'] = temp_ws;

在 excel sheet 我得到:

 __________________
|  0  |  1  |  2  |
-------------------
|  1  |  3  |  5  | 
|  2  |  4  |  6  | 
-------------------

我想得到这个:

 _____________________________
|  param1  |  1  |  3  |  5  |
|  param2  |  2  |  4  |  6  |
------------------------------

如何轻松获得?

这应该能为您提供所需的内容:

function transpose(a) {
    return Object.keys(a[0]).map(function(c) {
      let ret=a.map(function(r) { return r[c]; });
      ret.unshift(c); return ret;
    });
};

// or in ES6 notation:
const transp = a => Object.keys(a[0]).map(c=>{
  let ret=a.map(r=>r[c]); ret.unshift(c); 
  return ret; });

//example for JSON (in the program I get a long JSON in this shape)
const sheet_arr = [{'param1': 1, 'param2': 2},{'param1': 3, 'param2': 4},{'param1': 5, 'param2': 6}] ;

console.log(transpose(sheet_arr));
console.log(transp(sheet_arr));
.as-console-wrapper {max-height:100% !important}

我只是将键添加为每行中的第一个元素,使用 Array.unshift()