Home > Software design >  Google script; setValues from API
Google script; setValues from API

Time:05-28

I have problems set the values of an API into google sheets. The data set which is provided looks like this:

  const data = [
  {
    quantity: 10000,
    unitprice: 30.37,
    id: 168586
  },
  {
    quantity: 2000,
    unitprice: 27.85,
    id: 168583
  },
  {
    quantity: 20,
    unitprice: 150000,
    id: 135693
  },
  {
    quantity: 2109,
    unitprice: 25.01,
    id: 168586
  },
  {
    quantity: 8434,
    unitprice: 34.72,
    id: 168589
  },
  {
    quantity: 1,
    unitprice: 5,
    id: 168583
  },
  {
    quantity: 560,
    unitprice: 180.23,
    id: 158191
  }
];

If I use the setValue function in google sheets it only paste the first block but ignores the other ones. If I use setValues I get the error: "Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues."

Someone has an idea what I can do?

CodePudding user response:

Your data is not a 2D array, you have to detail each object with their properties

Try

function decode() {
  const data = [
    {
      quantity: 10000,
      unitprice: 30.37,
      id: 168586
    },
    {
      quantity: 2000,
      unitprice: 27.85,
      id: 168583
    },
    {
      quantity: 20,
      unitprice: 150000,
      id: 135693
    },
    {
      quantity: 2109,
      unitprice: 25.01,
      id: 168586
    },
    {
      quantity: 8434,
      unitprice: 34.72,
      id: 168589
    },
    {
      quantity: 1,
      unitprice: 5,
      id: 168583
    },
    {
      quantity: 560,
      unitprice: 180.23,
      id: 158191
    }
  ];
  let values = []
  values.push(['quantity', 'unitprice', 'id'])
  data.forEach(d => {
    values.push([d.quantity, d.unitprice, d.id])
  })
  SpreadsheetApp.getActiveSheet().getRange(1, 1, values.length, values[0].length).setValues(values)
}

enter image description here

  • Related