[GIS] Appending Data to FeatureLayer in ArcGIS API for JavaScript

arcgis-javascript-apifeature-layerjavascriptjson

I am working on a web app where I am making calls to a database api and it returns a JSON Object. I've managed to do so successfully as well as any manipulations that need be done.

Is there a way to add new fields to a FeatureLayer and the subsequently populate with the relevant data?

I do not necessarily want to edit the feature layer, just attach data on the fly so that I can then use it for analysis such as heat maps and what not. Have not really found anything concrete in the api documentation.

Ive tried the following code that results in an error. Fairly certain it is because i am trying to set the value before I add the Field.

featureLayer = new FeatureLayer(....);
fieldName = x;
value = y;  

featureLayer.graphics.attributes.fieldName = value;

Best Answer

See the JS API documentation for Graphic attr() method:

https://developers.arcgis.com/javascript/jsapi/graphic-amd.html#attr

You would do this for each feature Graphic in the layer, after loaded:

for (var i=0; i< featureLayer.graphics.length; i++) {
    var lookupId = featureLayer.graphics[i].attributes.myLookupFieldId;

       ... perhaps get values for x, y using lookupId ...

    featureLayer.graphics[i].attr(x,y);
}

Note that this only adds the field to the members of the graphics collection in the map layer (on the fly, as you suggest). If the features are re-loaded, you would have to re-iterate and attach the data again.

You get the values from each graphic by referencing the esri attributes property:

var thisValue = thisGraphic.attributes[x];

    or, assuming x == "newFieldName"

var thisValue = thisGraphic.attributes.newFieldName; 

Best, Bill B