2

I'm hoping someone can help me get the following getJson call going. I want to retrieve all the names which are buried in under features.attributes.NAME. See the sample json

  {
    "objectIdFieldName": "FID",   
    "globalIdFieldName": "",
    "geometryType": "esriGeometryPolygon",
    "spatialReference": {},
    "fields": [],
    "features": [
        {
            "attributes": {
                "NAME": "ST. JOHNS"
            }
        },
        {
            "attributes": {
                "NAME": "HAYDEN ISLAND"
            }
        }
    ]
}

Using jquery I'm currently trying something like this to create a blank array and push the names into it.

$.getJSON("url/myjson", function(data) {
    items = [];
    $.each( data, function(i) {
        items.push(data.features.attributes.NAME);
    });
});

The error I'm getting at the moment says Cannot read property 'NAME' of undefined.

1
  • I was having issues like this, and what I was missing was actually parsing in the JSON received into an object. Until you do that, you cannot actually reference into the JSON with data.features (or whatever properties you have in the JSON). Here: var obj = $.parseJSON(data); Now you can do what you need to do with: items.push(obj.features.attributes.NAME); Commented Dec 7, 2017 at 14:45

2 Answers 2

5

You need to use something like this:

var items = []; // empty array
$.each( data.features, function(index, value) {
  items.push(value.attributes.NAME);
});

The first parameter of the each function needs to be an array. You passed the whole object to it, containing the fields objectIdFieldName and so on.. I've changed that to pass only the features-array.

The next issue was with the callback you provided. It has two parameters: index and value. Index is the number of the current loop round. In value are the data you wanted to access.

Then I also changed the items.push-call appropriately.

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that $.each will tread the first argument as an array-like object. data returned from getJSON is your object, not an array.

Doing the following

var items = $.map(data.features, function (i) {
    return i.attributes.NAME;
});
console.log(items);

produces [ "ST. JOHNS", "HAYDEN ISLAND" ].

This has the added benefit of not relying on side-effects in the callback for each, by using map. This means you don't need to push elements into the array, as they are constructed from the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.