0

I have the following code which is meant to generate a new feature with some random values and add it to an array. The problem I have is that through every loop the objects already in the FeatureList array is being overwritten with the new object. I understand that the objects are being passed by ref and have tried the creating local instances of the object before pushing it to the array and also tried using slice to disconnect the tempArr but it still keeps happening.

Please can someone help me !!! thanks

let FeatureList = [];

generateFeature=(type)=>{
    var tempArr = [];
    var newFeature = {};
    newFeature = featureTemplate;
    newFeature.properties.title = getRandomTitle(type);
    newFeature.properties.description = newFeature.properties.title;
    newFeature.properties.url = getUrl(type);
    newFeature.properties.type = getType(type);
    newFeature.properties.status = getStatus(type);

    var newGeoms = []
    newGeoms.push(parseFloat(getRandomLatLon()));
    newGeoms.push(parseFloat(getRandomLatLon()));
    newGeoms.push(getRandomHeight());
    
    newFeature.geometry.coordinates = newGeoms;
    newFeature.id = getRandomId(type);

    tempArr.push(newFeature);
    FeatureList.push(tempArr.slice(0));
    tempArr = [];
}


fc =(type)=> {
    for (let i = 0; i < 30; i++) {
        generateFeature(type); 
    }
}

fc("Waterpump");
data.features = FeatureList;
Genesis
  • 1
  • 1
  • At `newFeature = featureTemplate;` you need to clone your `featureTemplate` object instead of just creating an additional reference to it ... – derpirscher Aug 02 '21 at 09:16
  • The problem is that `newFeature = featureTemplate` doesn't make a *copy*, it just makes `newFeature` and `featureTemplate` both refer to the **same** object. You're just reusing one object over and over. As derpirscher said, you have to make a copy of it (a deep one since it has nested objects). But does `featureTemplate` have things on it other than the things you're overwriting? Because if not, there's no need for it just do `let newFeature = { properties: { title: getRandomTitle(type), url: gtUrl(type), /*...*/} }; newFeature.description = newFeature.title;` – T.J. Crowder Aug 02 '21 at 09:19
  • Thanks so much for your help @derpirscher, I couldn't see where I was going wrong – Genesis Aug 02 '21 at 15:53
  • 1
    Thanks for much for the additional advice @T.J.Crowder, bit of a ...doh... moment when read your advice :) – Genesis Aug 02 '21 at 15:54

0 Answers0