Seems like this should be simple, but I'm stumped. I want to modify this sample to output to the console the list of fields for the loaded FeatureLayer. See below. The only modification I made was to add line 65: console.log(states);
That works fine, and shows there is attribute called "fields" for the layer states. However, on the next line when I try log console.log(states.fields); it says it is undefined. Why? And the bigger question, how do I get the list of fields?
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no"> <title></title> <link rel="stylesheet" href="https://community.esri.com//js.arcgis.com/3.13/esri/css/esri.css"> <style> html, body, #map { height: 100%; width: 100%; margin: 0; padding: 0; } </style> <script src="//js.arcgis.com/3.13/"></script> <script> var map; require([ "esri/map", "esri/geometry/Extent", "esri/layers/FeatureLayer", "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/TextSymbol", "esri/renderers/SimpleRenderer", "esri/layers/LabelLayer", "esri/Color", "dojo/domReady!" ], function( Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol, TextSymbol, SimpleRenderer, LabelLayer, Color ) { // load the map centered on the United States var bbox = new Extent({"xmin": -1940058, "ymin": -814715, "xmax": 1683105, "ymax": 1446096, "spatialReference": {"wkid": 102003}}); map = new Map("map", { extent: bbox }); var labelField = "STATE_NAME"; // create a renderer for the states layer to override default symbology var statesColor = new Color("#666"); var statesLine = new SimpleLineSymbol("solid", statesColor, 1.5); var statesSymbol = new SimpleFillSymbol("solid", statesLine, null); var statesRenderer = new SimpleRenderer(statesSymbol); // create a feature layer to show country boundaries var statesUrl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3"; var states = new FeatureLayer(statesUrl, { id: "states", outFields: [labelField] }); states.setRenderer(statesRenderer); map.addLayer(states); console.log(states); console.log(states.fields); // create a text symbol to define the style of labels var statesLabel = new TextSymbol().setColor(statesColor); statesLabel.font.setSize("14pt"); statesLabel.font.setFamily("arial"); var statesLabelRenderer = new SimpleRenderer(statesLabel); var labels = new LabelLayer({ id: "labels" }); // tell the label layer to label the countries feature layer // using the field named "admin" labels.addFeatureLayer(states, statesLabelRenderer, "{" + labelField + "}"); // add the label layer to the map map.addLayer(labels); }); </script> </head> <body> <div id="map"></div> </body> </html>
Solved! Go to Solution.
Here's an example that shows how to output the field info and/or the field name to the console.
states.on("load", function(){ for(i = 0; i < states.fields.length; i++){ //write out field info console.log(dojoJson.toJson(states.fields)); //write out just field name console.log(states.fields.name); } });
In order to format the field info in a way that's easier for you to copy/paste I use the toJson method which means you'll need to require the dojo/_base/json module.
require([ "esri/map", "esri/geometry/Extent", "esri/layers/FeatureLayer", "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/TextSymbol", "esri/renderers/SimpleRenderer", "esri/layers/LabelLayer", "esri/Color", "dojo/_base/json", "dojo/domReady!" ], function( Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol, TextSymbol, SimpleRenderer, LabelLayer, Color, dojoJson
Looks like you accidentally posted this in the GeoNet Help section. It should probably be in ArcGIS API for JavaScript
Oops. Is there a way I can change where this is posted, or should I just create a new post over there?
I've moved it for you.
Paste a copt of the console.log in here. I bet it has to do with states[0].fields or something in the object.
I struggling copying the Object out of my console. Below is what I get when I right-click the Object in the Chrome browser and copy it. Is there a better way?
yField":"STATE_NAME","typeIdField":null,"fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null},{"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null},{"name":"STATE_NAME","type":"esriFieldTypeString","alias":"STATE_NAME","length":25,"domain":null},{"name":"STATE_FIPS","type":"esriFieldTypeString","alias":"STATE_FIPS","length":2,"domain":null},{"name":"SUB_REGION","type":"esriFieldTypeString","alias":"SUB_REGION","length":20,"domain":null},{"name":"STATE_ABBR","type":"esriFieldTypeString","alias":"STATE_ABBR","length":2,"domain":null},{"name":"POP2000","type":"esriFieldTypeInteger","alias":"POP2000","domain":null},{"name":"POP2007","type":"esriFieldTypeInteger","alias":"POP2007","domain":null},{"name":"POP00_SQMI","type":"esriFieldTypeDouble","alias":"POP00_SQMI","domain":null},{"name":"POP07_SQMI","type":"esriFieldTypeDouble","alias":"POP07_SQMI","domain":null},{"name":"WHITE","type":"esriFieldTypeInteger","alias":"WHITE","domain":null},{"name":"BLACK","type":"esriFieldTypeInteger","alias":"BLACK","domain":null},{"name":"AMERI_ES","type":"esriFieldTypeInteger","alias":"AMERI_ES","domain":null},{"name":"ASIAN","type":"esriFieldTypeInteger","alias":"ASIAN","domain":null},{"name":"HAWN_PI","type":"esriFieldTypeInteger","alias":"HAWN_PI","domain":null},{"name":"OTHER","type":"esriFieldTypeInteger","alias":"OTHER","domain":null},{"name":"MULT_RACE","type":"esriFieldTypeInteger","alias":"MULT_RACE","domain":null},{"name":"HISPANIC","type":"esriFieldTypeInteger","alias":"HISPANIC","domain":null},{"name":"MALES","type":"esriFieldTypeInteger","alias":"MALES","domain":null},{"name":"FEMALES","type":"esriFieldTypeInteger","alias":"FEMALES","domain":null},{"name":"AGE_UNDER5","type":"esriFieldTypeInteger","alias":"AGE_UNDER5","domain":null},{"name":"AGE_5_17","type":"esriFieldTypeInteger","alias":"AGE_5_17","domain":null},{"name":"AGE_18_21","type":"esriFieldTypeInteger","alias":"AGE_18_21","domain":null},{"name":"AGE_22_29","type":"esriFieldTypeInteger","alias":"AGE_22_29","domain":null},{"name":"AGE_30_39","type":"esriFieldTypeInteger","alias":"AGE_30_39","domain":null},{"name":"AGE_40_49","type":"esriFieldTypeInteger","alias":"AGE_40_49","domain":null},{"name":"AGE_50_64","type":"esriFieldTypeInteger","alias":"AGE_50_64","domain":null},{"name":"AGE_65_UP","type":"esriFieldTypeInteger","alias":"AGE_65_UP","domain":null},{"name":"MED_AGE","type":"esriFieldTypeDouble","alias":"MED_AGE","domain":null},{"name":"MED_AGE_M","type":"esriFieldTypeDouble","alias":"MED_AGE_M","domain":null},{"name":"MED_AGE_F","type":"esriFieldTypeDouble","alias":"MED_AGE_F","domain":null},{"name":"HOUSEHOLDS","type":"esriFieldTypeInteger","alias":"HOUSEHOLDS","domain":null},{"name":"AVE_HH_SZ","type":"esriFieldTypeDouble","alias":"AVE_HH_SZ","domain":null},{"name":"HSEHLD_1_M","type":"esriFieldTypeInteger","alias":"HSEHLD_1_M","domain":null},{"name":"HSEHLD_1_F","type":"esriFieldTypeInteger","alias":"HSEHLD_1_F","domain":null},{"name":"MARHH_CHD","type":"esriFieldTypeInteger","alias":"MARHH_CHD","domain":null},{"name":"MARHH_NO_C","type":"esriFieldTypeInteger","alias":"MARHH_NO_C","domain":null},{"name":"MHH_CHILD","type":"esriFieldTypeInteger","alias":"MHH_CHILD","domain":null},{"name":"FHH_CHILD","type":"esriFieldTypeInteger","alias":"FHH_CHILD","domain":null},{"name":"FAMILIES","type":"esriFieldTypeInteger","alias":"FAMILIES","domain":null},{"name":"AVE_FAM_SZ","type":"esriFieldTypeDouble","alias":"AVE_FAM_SZ","domain":null},{"name":"HSE_UNITS","type":"esriFieldTypeInteger","alias":"HSE_UNITS","domain":null},{"name":"VACANT","type":"esriFieldTypeInteger","alias":"VACANT","domain":null},{"name":"OWNER_OCC","type":"esriFieldTypeInteger","alias":"OWNER_OCC","domain":null},{"name":"RENTER_OCC","type":"esriFieldTypeInteger","alias":"RENTER_OCC","domain":null},{"name":"NO_FARMS97","type":"esriFieldTypeDouble","alias":"NO_FARMS97","domain":null},{"name":"AVG_SIZE97","type":"esriFieldTypeDouble","alias":"AVG_SIZE97","domain":null},{"name":"CROP_ACR97","type":"esriFieldTypeDouble","alias":"CROP_ACR97","domain":null},{"name":"AVG_SALE97","type":"esriFieldTypeDouble","alias":"AVG_SALE97","domain":null},{"name":"SQMI","type":"esriFieldTypeInteger","alias":"SQMI","domain":null},{"name":"Shape_Length","type":"esriFieldTypeDouble","alias":"Shape_Length","domain":null},{"name":"Shape_Area","type":"esriFieldTypeDouble","alias":"Shape_Area","domain":null}],"relationships":[],"canModifyLayer":true,"canScaleSymbols":false,"hasLabels":false,"capabilities":"Data,Map,Query","maxRecordCount":1000,"supportsStatistics":true,"supportsAdvancedQueries":true,"supportedQueryFormats":"JSON, AMF","ownershipBasedAccessControlForFeatures":{"allowOthersToQuery":true},"useStandardizedQueries":true,"advancedQueryCapabilities":{"useStandardizedQueries":true,"supportsStatistics":true,"supportsOrderBy":true,"supportsDistinct":true,"supportsPagination":false,"supportsTrueCurve":true}}"_loadCallback: undefined_lyrZEHandle: Object_map: Object_mapTimeExtent: null_maxOffset: 5088_mode: Object_mouseEvents: true_newFeatures: Array[0]_nextId: 0_onExtentChangeHandler_connect: Object_onPanEndHandler_connect: Object_onPanHandler_connect: Object_onPanStartHandler_connect: null_onZoomStartHandler_connect: Object_onclick_connect: Object_ondblclick_connect: Object_onmousedown_connect: Object_onmousemove_connect: Object_onmouseout_connect: Object_onmouseover_connect: Object_onmouseup_connect: Object_optEditable: undefined_orderBy: null_outFields: Array[1]_params: Object_plugins: Object_processEvent: function (){return f.apply(a,arguments||[])}_refresh: function (){return f.apply(a,arguments||[])}_rendererFields: Array[0]_resized: false_resumedOnce: true_rndForScale: undefined_selectHandler: function (){return f.apply(a,arguments||[])}_selectedFeatures: Object_selectedFeaturesArr: Array[0]_setMap: function (b){var c=e.apply(this,_srInfo: undefined_task: Object_tileHeight: 512_tileWidth: 512_timeConnect: null_trackIdField: undefined_ulid: 0_url: Object_usePatch: true_wakeTimer: null_wrap: false_zoomConnect: ObjectadvancedQueryCapabilities: ObjectallowGeometryUpdates: trueattributionDataUrl: ""canModifyLayer: truecanScaleSymbols: falsecapabilities: "Data,Map,Query"className: undefinedcopyright: "US Bureau of the Census: http://www.census.gov"credential: undefinedcurrentMode: 1dataAttributes: undefineddefaultDefinitionExpression: undefineddefaultVisibility: truedescription: "This service presents various population statistics from Census 2000, including total population, population density, racial counts, and more. The map service presents statistics at the state, county, block group, and block point levels.↵"disableMouseEvents: function (){return f.apply(a,arguments||[])}displayField: "STATE_NAME"editFieldsInfo: undefinededitSummaryCallback: undefinedenableMouseEvents: function (){return f.apply(a,arguments||[])}fields: Array[52]0: Object1: Object2: Object3: Object4: Object5: Object6: Object7: Object8: Object9: Object10: Object11: Object12: Object13: Object14: Object15: Object16: Object17: Object18: Object19: Object20: Object21: Object22: Object23: Object24: Object25: Object26: Object27: Object28: Object29: Object30: Object31: Object32: Object33: Object34: Object35: Object36: Object37: Object38: Object39: Object40: Object41: Object42: Object43: Object44: Object45: Object46: Object47: Object48: Object49: Object50: Object51: Objectlength: 52__proto__: Array[0]fullExtent: ObjectgdbVersion: undefinedgeneralizeForScale: 4000geometryType: "esriGeometryPolygon"globalIdField: undefinedgraphics: Array[49]hasAttachments: falsehasAttributionData: falsehasLabels: falsehtmlPopupType: "esriServerHTMLPopupTypeNone"i18n: aid: "states"indexedFields: undefinedinfoTemplate: undefinedinitialExtent: ObjectisDataVersioned: undefinedlatticeTiling: undefinedlayerId: 3loaded: truemaxPointCountForAuto: 4000maxRecordCount: 1000maxRecordCountForAuto: 2000maxVertexCountForAuto: 250000mode: 1multipatchOption: undefinedname: "states"normalization: trueobjectIdField: "OBJECTID"onEditsComplete: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onError: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onGraphicNodeAdd: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onLabelingInfoChange: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onLoad: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onResume: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onShowLabelsChange: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onSuspend: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||onUpdateEnd: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||ontime-extent-change: function (){for(var a=p,b=arguments,c=h.before;c;)b=c.advice.apply(this,b)||orderByFields: undefinedownershipBasedAccessControlForFeatures: Objectquantize: undefinedqueryPagination: falserefresh: function (){return f.apply(a,arguments||[])}refreshInterval: 0relationships: Array[0]renderer: ObjectshowLabels: truesource: undefinedspatialReference: Objectstatistics: undefinedstyling: truesupportsAdvancedQueries: truesupportsAttachmentsByUploadId: undefinedsupportsCalculate: undefinedsupportsCoordinatesQuantization: undefinedsupportsRollbackOnFailure: undefinedsupportsRollbackOnFailureParameter: undefinedsupportsStatistics: truesuspended: falsesyncCanReturnChanges: undefinedtemplates: Array[0]type: "Feature Layer"typeIdField: nulltypes: Array[0]updating: falseurl: "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3"useMapTime: trueuserId: undefineduserIsAdmin: undefinedversion: 10.3visibilityField: undefinedvisibleAtMapScale: true__proto__: Object
Here's an example that shows how to output the field info and/or the field name to the console.
states.on("load", function(){ for(i = 0; i < states.fields.length; i++){ //write out field info console.log(dojoJson.toJson(states.fields)); //write out just field name console.log(states.fields.name); } });
In order to format the field info in a way that's easier for you to copy/paste I use the toJson method which means you'll need to require the dojo/_base/json module.
require([ "esri/map", "esri/geometry/Extent", "esri/layers/FeatureLayer", "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/TextSymbol", "esri/renderers/SimpleRenderer", "esri/layers/LabelLayer", "esri/Color", "dojo/_base/json", "dojo/domReady!" ], function( Map, Extent, FeatureLayer, SimpleLineSymbol, SimpleFillSymbol, TextSymbol, SimpleRenderer, LabelLayer, Color, dojoJson
Perfect! Thanks!
After looking at your code it appears the reason mine wasn't working was because the layers wasn't loaded yet.
Nice trick with the .toJson. That is really handy!