How can I retrieve data within an array from an API call in Google script? - arrays

I'm pretty new, so bear with me.
I'm making a Google script that will let me call the TMDb API and get some information from a movie list I'm compiling for myself. I'm trying to get all the values to automatically fill by just using the TMDB ID.
After struggling, I found it was easiest to create a function for each column I want to fill (title, date, genre, poster url, etc.) and pass the input from the cell in the spreadsheet to be able to retrieve the info, then return the data to that cell.
I can't figure it out though, when it comes to the "genre" category, because it's in an array.
Here's my code that works for a different column:
function getPoster(input) {
var movieID = input
// Call the TMDB API for movie details
var response = UrlFetchApp.fetch("https://api.themoviedb.org/3/movie/" + movieID + "?api_key=<<mykey>>");
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
return data["poster_path"];
}
Using the API data:
"poster_path":"/hXLScIERphkTsMGdfKKvF4p4SPB.jpg",
However, the "genre" category lists them as an array:
"genres":[{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}],
How can I write the return so that it sends a string with the shown genres "Action, Drama, Thriller" into the single corresponding cell (not spilling into adjacent cells), while also ignoring the "id"?

you need to create an array from the genre's name values.
use this snippet:
var genres = [{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}];
// Return "Action, Drama, Thriller" as a string into a single cell
return genres.map(function(genre){
return genre.name;
}).join(", ");
Sample output when printed:

Related

Create drop down menu from external JSON in Javascript

I am using an external JSON to retrieve the name of the volcano and put all names into a drop down menu to be selected and shown on my map. Currently, I have no errors on my webpage console but I am not getting any names inside the dropdown. I am very new to coding and I am blank on what is wrong. Any advice?
'''
//Call JSON for map latitude and longitude, showing volcaones locations
// with last eruption in a hover feature
var data = {};
d3.json("./Graphs/Vol_cleaned.json").then(function (data) {
console.log(data);
// Once we get a response, send the data.features object to the createFeatures function
makeMap(data);
makeDrop();
});
//MAKE DROP DOWN MENU TO SELECT VOLCANO NAME
function makeDrop(){
for (var i = 0; i < data.Volcano_Name; i++){
let name = data.Volcano_Name[i];
d3.select("#arr").append("option").text(name);
}
}
function optionChanged() {
makeMap(data);
}
function makeMap(data) {
'''
JSON
I have tried several ways to call the data, I don't think I will be able to describe them correctly being that I am new to the coding world. My current code in the picture provide is working with no errors but nothing is populated in the drop down.

Compare data between two Arrays containing custom Swift Objects

I have some data I have received through an API that return JSON to me. I know I can fetch it and store relevant info from the API into my iOS app. But only while the app is running. I.E. I have not implemented YET how to store the info fetched from the API into UserDefalults. Working on this feature I ran into a problem.
I have two Arrays that keeps track of my data. The first Array is the Array I want to store in UserDefaults when I have fetch my data. This one is called "lenders" and keeps LenderData
The second Array is my temporary Array. It contains the same type of objects, and this is the one I want to populate with data from the API and then compare to my existing Array "lenders".
I want to check if the "lenders" Array contains any object that has the same id as the object I'm looking at in the "lendersTemp" array. If the lenders Array does not contain any LederData object with the id of the tempLender we are currently looking at, we add the tempLender into the lenders Array. How would I go about doing this?
My current (non-working) solution is as follows:
var lenders = [LenderData]()
var lendersTemp = [LenderData]()
...
// Get JSON DATA
...
for tempLender in self.lendersTemp {
if !self.lenders.contains(where: {$0.id == tempLender.id}) {
self.lenders.append(tempLender)
}
}
EDIT:
My view did load method:
var lenders = [LenderData]()
var lendersTemp = [LenderData]()
override func viewDidLoad() {
super.viewDidLoad()
downloadJSON {
self.myTableView.reloadData()
}
self.myTableView.rowHeight = 90
myTableView.delegate = self
myTableView.dataSource = self
}
I figured it out with some help! So this is my answer to my own question!
My problem was that getting data from my API is done with an asyc method. And I tried to do comparison after the reload method was called on my TableView. So I did not populate the array the tableview is getting data from, before after the reloadData() had been called and therefore it seemed like my tableview and comparison algorithm, did not work, when in fact it did!

Passing array value to a query string url

I have an array of id let's say
favorites = [102,110,112,125]
I want to retrieve the corresponding object for each id by passing it to query string like this :
public getFavorites(favs){
let favorites = favs.join();
let encodedUrl = encodeURIComponent(JSON.stringify({"id": favorites }));
return this.http.get(this.api_url + '/1/query/data/getFavs?parameters='+encodedUrl, {
headers: this.authHeader
})
.retry(3)
.map(res => res.json());
}
The problem is only one object appear in my html template and also in the console. What is the best way for me to pass an array of value to a URL as parameters in order to retrieve the associated objects?
You can pass multiple parameter values with the same name over the querystring. Does that help you? For example, here's a snippet:
this.api_url + '/1/query/data/getFavs?id=101&id=110
Here is another answer that has some more info on this.
If you have to send the ID's over in a serialized manner, consider posting the JSON instead of using the GET method. If you're trying to maintain adherence to REST verb standards by making it a get call, can you post the server code?

Select users not in array of pointers

Using Parse.com and its Cloud code, I want to fetch users that are not in array of users.
...
var query = new Parse.Query(Parse.User);
query.notContainedIn("objectId", request.object.get("recipients"));
...
query.find().then(
function(results) {
console.log("# of users:" + results.length);
},
function(error) {
console.error(error)
}
);
The constraint notContainedIn doesn't seem to work, all users are returned, not just the ones not contained in the recipients array coming as part of the request object.
The recipients array in REST request is defined like this
"recipients":[
{"__type":"Pointer","className":"_User","objectId":"qwerty1234"},
{"__type":"Pointer","className":"_User","objectId":"asdfgh1234"}]
The data I get as part of the request is ok, because e.g. request.object.get("recipients")[0].id returns the qwerty1234 value.
What am I doing wrong here?
You are asking parse to compare the objectId to an array of pointers. This would work fine if the column was a Pointer to a User, but you're using just the ID.
The easy solution is to map or extract the ID from the array of pointers, e.g.
// at the top, so you can use the Underscore library
var _ = require('underscore');
// ...
// in your Cloud function
var query = new Parse.Query(Parse.User);
// _.pluck() creates an array of a property from each object in the parent array
var recipientObjectIds = _.pluck(request.object.get('recipients'), 'objectId');
query.notContainedIn('objectId', recipientObjectIds);

Query to Salesforce returns columns out of order

I've developed a Google Apps script to pull some data from a custom object in Salesforce and have my columns in this order:
SELECT Component__r.Name, Component__c, Product__c, Story_Name__c, Description__c, id , Product_Id__c, Priority__c , StoryName FROM Story__c WHERE Product_Id__c
However, my results into a Google Spreadsheet come in this order:
StoryName Component__r Component__c Product__c Product_Id__c Priority__c Id Description__c Story_Name__c
I'm told that it's no unusual for SOQL queries to return data in a different order than the query. Do anyone know of a method/function/process to use to get the columns to appear on the spreadsheet in the order of the query? I'd like to do it prior to placing the columns on the spreadsheet, but if there's no other method, that's ok.
My data is pulled back in this function:
function renderGridData(object, renderHeaders){
var sheet = SpreadsheetApp.getActiveSheet();
var data = [];
var sObjectAttributes = {};
//Need to always build headers for row length/rendering
var headers = buildHeaders(object.records);
if(renderHeaders){
data.push(headers);
}
for (var i in object.records) {
var values = [];
for(var j in object.records[i]){
if(j!="attributes"){
values.push(object.records[i][j]);
} else {
var id = object.records[i][j].url.substr(object.records[i][j].url.length-18,18);
//Logger.log(id);
sObjectAttributes[id] = object.records[i][j].type;
}
}
data.push(values);
}
Logger.log(sheet.getLastRow());
var destinationRange = sheet.getRange(sheet.getLastRow()+1, 1, data.length, headers.length);
destinationRange.setValues(data);
}
Thanks for any advice.
The Partner SOAP APi is the only API that will try to preserve the field order from the query into the results structure.
For JSON based responses from the REST API, JSON specifically says that objects key/values are unordered, so a response that would preserve the order would need to use a different JSON structure (an array of key/value objects) which would be significantly more verbose.

Resources