Home > OS >  How can put the values back to the spreadsheet, matching the col headers with the object keys using
How can put the values back to the spreadsheet, matching the col headers with the object keys using

Time:10-19

I can grab the values from a defined range and build an object - thanks to this awesome resource. However, the second part is not really clear to me, as the resulting object keys, being embraced in ' makes it behave like a string instead of a key?

This is the code used to get the range's values as an oject:

function savePoEntry2() {
  let data = [
    ["F. Factura\nInvoice Date", "Vence\nExpires on", "# Factura\nInvoice #", "T. Parcial\nSubtotal", "IVA\n%", "IVA\n$", "RTE FTE\n", "TOTAL PESOS\n", "", "TRM\n", "USD\n", "Diferencia\nVariance"],
    ["2022-10-18T05:00:00.000Z", "2022-10-18T05:00:00.000Z", 1547, 10000000, 0.15, 1500000, 200, 11499800, "", 4500, 2555.511111111111, ""]
  ];

  const [headers, ...rows] = data;
  const res = rows.map((r) =>
    headers.reduce((o, h, j) => Object.assign(o, {
      [h]: r[j]
    }), {})
  );
  console.log(Object.values(res));
}

Appreciate your help!

CodePudding user response:

function savePoEntry2() {
  let data = [
    ["F. Factura\nInvoice Date", "Vence\nExpires on", "# Factura\nInvoice #", "T. Parcial\nSubtotal", "IVA\n%", "IVA\n$", "RTE FTE\n", "TOTAL PESOS\n", "", "TRM\n", "USD\n", "Diferencia\nVariance"],
    ["2022-10-18T05:00:00.000Z", "2022-10-18T05:00:00.000Z", 1547, 10000000, 0.15, 1500000, 200, 11499800, "", 4500, 2555.511111111111, ""]
  ];
  //const ss = SpreadsheetApp.getActive();//test
  //const sh = ss.getSheetByName("Sheet0");//test
  //const vs = sh.getDataRange().getValues();//test
  const [headers, ...rows] = data;
  const res = rows.map((r) => headers.reduce((a, h, j) => Object.assign(a, { [h]: r[j] }), {}));
  console.log(JSON.stringify(res));
  let o = res.map(r => { 
    let row = []
    headers.forEach(h =>  row.push(r[h]) )
    return row;
    });
    o.unshift(headers)
  Logger.log(JSON.stringify(o));//You can use o with setValues();
}
  • Related