Search code examples
replaceshapesfeature-extractiongoogle-earth-engine

Replacing string values in a FeatureCollection with numbers in google earth engine


I have a FeatureCollection with a column named Dominance which has classified regions into stakeholder dominance. In this case, Dominance contains values as strings; specifically 'Small', 'Medium', 'Large' and 'Others'. I want to replace these values/strings with 1,2,3 and 4. For that, I use the codes below:

var Shape = ee.FeatureCollection('XYZ')
var Shape_custom = Shape.select(['Dominance'])

var conditional = function(feat) {
  return ee.Algorithms.If(feat.get('Dominance').eq('Small'),
  feat.set({class: 1}),
  feat)
}
var test = Shape_custom.map(conditional)
## This I plan to repeat for all classes

However, I am not able to change the values. The error I am getting is feat.get(...).eq is not a function. What am I doing wrong here?


Solution

  • The simplest way to do this kind of mapping is using a dictionary. That way you do not need more code for each additional case.

    var mapping = ee.Dictionary({
      'Small': 1,
      'Medium': 2,
      'Large': 3,
      'Others': 4
    });
    
    var mapped = Shape
      .select(['Dominance'])
      .map(function (feature) {
        return feature.set('class', mapping.get(feature.get('Dominance')));
      });
    

    https://code.earthengine.google.com/8c58d9d24e6bfeca04e2a92b76d623a2