Search code examples
javascriptopenlayers

Deep cloning of feature attributes in OpenLayers


I need to make a clone of a feature in OpenLayers (I am using latest 6.3.1 version, but my question is not version specific, I guess).

The feature itself has a method .clone(). Unfortunately, my attributes/properties defined for feature are objects and arrays and .clone method does only shallow copy of the feature. So if I change some value in the cloned object, the original object is changed too.

So, how to make a deep copy of a feature in OpenLayers?


Solution

  • As Anatoly suggested in comments, it can be done by .setProperties() method.

    EDIT 18.4.2020: As geometry of the feature is included in .getProperties() and it cannot be copied properly with JSON.parse()/JSON.stringify(), I had to add one more line to the original code, setting geometry property of clonedProperties.

    My code (without any external library) is as follows:

    const clonedFeature = feature.clone();
    const clonedProperties = JSON.parse(JSON.stringify(feature.getProperties()));
    clonedProperties.geometry = clonedFeature.getGeometry(); // see EDIT
    // Maybe do something with clonedProperties as I do.
    clonedFeature.setProperties(clonedProperties, true);