Iterate Over ArcGIS Online Table using Javascript

763
1
06-09-2021 04:27 PM
MikeMacRae
Occasional Contributor III

I am trying to learn how to iterate over a table stored as a feature service in my ArcGIS Online Content. I am just getting started with the Javascript API for ArcGIS so my knowledge isn't top level yet.

What I am trying to do it dynamically update a URL using values from 2 columns in the table. I want to iterate through each row and grab the value from the 2 columns and inject them into a URL via concatenation.

Drawing from my python background, it would be something like:

 

URL = www.mywebsite.com

for row in cursor:
    URL + "\" + row[1] + "some_other_URL_string_stuff" + row[2]

 

 

I think what I need to do is use the following code to do so, but

  1. I am not sure how to reference the table in the script. I've tried setting the element ID to the GUID of the feature table but that doesn't seem to work. I've also tried the name. I've combed through the Javascript help docs, but they are difficult to navigate and I can't seem to find examples of what I am trying to do.
  2. I don't really know how to concatenate the values from the columns in the table using javascript.

 

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }  
}

 

 

0 Kudos
1 Reply
BlakeTerhune
MVP Regular Contributor

It's just like querying a feature layer. You can get the url for the table item in ArcGIS Online, plug it into a QueryTask, execute the Query, then iterate over the results. Here's an example:

var qTask = new QueryTask({
  url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SpatioTemporalAggregation/RainfallTimeSeriesDataIllinois/MapServer/8"
});

// Set the query parameters with a where clause and to return all fields.
var params = new Query({
  returnGeometry: false,
  where: "avg_monthly_rainfall > 100",
  outFields: ["*"]
});

// executes the query and handle the resulting FeatureSet.
qTask.execute(params)
.then(function(featureSet) {
  featureSet.features.forEach(function(feature) {
    console.log(feature);
    for (const [fieldName, fieldValue] of Object.entries(feature.attributes)) {
      // Do something with the field names and field values.
      console.log(`\t${fieldName}: ${fieldValue}`);
    }
  });
})
.catch(function (error) {
  console.error("Promise rejected: ", error.message);
});

 

0 Kudos