I get this back from my API call in Google Script Editor
"data": [ { "name": "page_engaged_users", "period": "day", "values": [ { "value": 13521, "end_time": "2021-02-22T08:00:00+0000" } ], "title": "Daily Page Engaged Users", "description": "Daily: The number of people who engaged with your Page. Engagement includes any click or story created. (Unique Users)", "id": "231123/insights/page_engaged_users/day" }, { "name": "page_post_engagements", "period": "day", "values": [ { "value": 18963, "end_time": "2021-02-22T08:00:00+0000" } ], "title": "Daily Post Engagements", "description": "Daily: The number of times people have engaged with your posts through like, comments and shares and more.", "id": "231123/insights/page_post_engagements/day" }, { "name": "page_impressions_unique", "period": "day", "values": [ { "value": 347696, "end_time": "2021-02-22T08:00:00+0000" }
I had a script that was working fine with a different call so i am using the same. The script is the below.
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = spreadsheet.getSheetByName('Sheet1'); var response = UrlFetchApp.fetch( "Api call"); var dataAll = JSON.parse(response.getContentText()); var dataSet = dataAll.data; var rows = [], data; for (i = 0; i < dataSet.length; i++) { data = dataSet[i]; rows.push([data.values[0].value]); //your JSON entities here } Logger.log(rows) sheet.getRange(sheet.getLastRow() + 1, 1, rows.length,1).setValues(rows); }
So when i push data.values[0].value i get all the values back but i just want the first. What am i doing wrong?
Advertisement
Answer
Your response data
is an array of objects. The for loop you have is iterating over that loop.
for (i = 0; i < dataSet.length; i++) { data = dataSet[i]; rows.push([data.values[0].value]); //your JSON entities here }
If you are looking to only push on the first Object’s value. You do not need the loop since you just are looking to grab what is at the first index of data. You can save time by just directly accessing the first position using dataSet[0]
such as dataSet[0].values[0].value
(you are already using this same method to access the first element of array values
)
Here is an example of how you can grab the first object in your data array’s value shown here – JSFiddle