Search code examples
javascriptgoogle-earth-engine

javascript - can't access property of an object using its key?


in Google Earth Editor, we've created an object using the reduceRegion() function:

var meanValue2015 = ndvi2015.reduceRegion({
  reducer: ee.Reducer.mean(),
  geometry: justEC15.geometry(),
  crs: 'EPSG:4326',
  scale: 30,
});

My issue is that meanValue2015 appears to be an object - I input

print(meanValue2015);
print(typeof(meanValue2015));
print(Object.keys(meanValue2015));

and get "Object (1 property) - NDVI: 0.3177...", "Object", and then "[ ]" respectively? And then

print(meanValue2015.NDVI);
print(meanValue2015['NDVI']);

is undefined? Is there something obvious I'm doing wrong here?


Solution

  • meanValue2015 is a Earth Engine object: a Dictionary. So..

    var meanValue2015 = ndvi2015.reduceRegion({
      reducer: ee.Reducer.mean(),
      geometry: justEC15.geometry(),
      crs: 'EPSG:4326',
      scale: 30,
    });
    
    var realValue = ee.Number(meanValue2015.get("ndvi"));
    print("real value (object):", realValue)
    
    // realValue is a EE object, so you have to use it as is..
    // this would be easy, but it is wrong..
    var newValueWrong = realValue + 1
    
    // this is the right way..
    var newValueRight = realValue.add(ee.Number(1))
    
    print("wrong:", newValueWrong)
    print("right:", newValueRight)
    
    // there is another way, but it is not recommendable because you'd
    // be wasting EE computing capacity (Google's gift! don't waste it)
    
    var localValue = realValue.getInfo() + 1
    
    print("value in the local scope (try to avoid)", localValue)