0

I have this array that's a response from an endpoint that looks like this:

{
  "dates": [
    {
      "date": "02-06-2021",
      "product": [
        {
          "id": "a1",
          "quantity": 10,
          "price": 10.99
         ]
        },
        {
          "id": "b2",
          "quantity": 43,
          "price": 17.99
        ]
       }]
    }

Is there a way where we can simply get the id and quantity for each product together? I know how to get it separately but not sure if it's possible to get it together:

var fetchData = UrlFetchApp.fetch(url, options);
var idData = JSON.parse(fetchData.getContentText());
var getIdData = idData.dates.map(dates => {return dates.product.map(product => {return product.id})});

var getQuantityData = idData.dates.map(dates => {return dates.product.map(product => {return product.quantity})});
4
  • "Is there a way..." - Not with that invalid syntax... Commented Jun 2, 2021 at 7:08
  • @Andreas hey at which part is it invalid? works fine for me. im wondering if can get it together instead of separately Commented Jun 2, 2021 at 7:12
  • You could just map product objects. Commented Jun 2, 2021 at 7:17
  • "at which part?" - The given input (response) is invalid. Commented Jun 2, 2021 at 7:42

1 Answer 1

2
iData = JSON.parse('{"dates":[{"date":"02-06-2021","product":[{"id":"a1","quantity":10,"price":10.99},{"id":"b2","quantity":43,"price":17.99}]}]}')
let A = idData.dates[0].product.map(obj => [obj.id,obj.quantity]);
A.unshift(['id','Quantity']);

A will be a two column 2 dimensional array that can be put into a spreadsheet with setValues() method.

sheet.getRange( 1,1,A.length,A[0].length).setValues(A);

Here's the entire function after fixing the sample JSON.

function testt() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet2')
  const idData = JSON.parse('{"dates":[{"date":"02-06-2021","product":[{"id":"a1","quantity":10,"price":10.99},{"id":"b2","quantity":43,"price":17.99}]}]}');
  let A = idData.dates[0].product.map(obj => [obj.id, obj.quantity]);
  A.unshift(['id', 'Quantity']);
  sh.getRange(1, 1, A.length, A[0].length).setValues(A);
}

Output:

id Quantity
a1 10
b2 43
Sign up to request clarification or add additional context in comments.

3 Comments

oh this is nice! thank you. will try it out
.map(({id, quantitiy}) => [ id, quantity ])
works like a charm! thanks for the detail explanation as well. i really appreciate it. thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.