2

Situation

I have a list of variables:

// Example data
var data_2016 = 7;
var data_2017 = 9;
var data_2018 = 5;
var data_2019 = 2;

I would like to loop through a selection of these variables, by specifying years, e.g. 2017 to 2019, ultimately applying a range of functions to the variables.

// Specified year range
var startyear = 2017;
var endyear = 2019;

// Set up loop: Make list of years
var years = [];
for (var j = startyear; j <= endyear; ++j) years.push(j);
var years = years.map(String);

// The main loop
var i;
for (i = 0; i < years.length; i++) {
   var yr = years[i];
   var img = 'data_' + yr;
   print(img);
}

Here is the link for this example.


Question

How do I call the actual variables, rather than just the string? In R, I would be using get() for this. The expected output for this example would be 9, 5, 2.

Tried so far

I have tried solutions for javascript, but none of them seem to work:

var img = 'data_' + yr
var img = window[img];

var img = 'data_' + yr
var img = eval[img];

var img = 'data_' + yr
var img = this[img];
1

Google Earth Engine is quite different to the usual javascript experience. You would almost never use for loops and most often dates are saved as properties (attached dictionaries) to Earth Engine Objects like ee.Image and ee.Feature.

I would suggest that you start out reading or watching some of the tutorials supplied by the GEE team.

EDIT:

But to actually give an answer to your question, depending on what kind of data you have you would do something like this:

// add Dates to ee.Image
var year_2017 = ee.Image.constant(1).set("system:time_start", "2017-01-01")
var year_2018 = ee.Image.constant(2).set("system:time_start", "2018-01-01")

// Compile all Images into a collection
var year_collection = ee.ImageCollection([year_2017, year_2018])

// Filter the collection to a specific Date
print(year_collection.filterDate("2017-01-01", "2017-12-31"))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.