Erik Grosskurth
Erik Grosskurth

Reputation: 3932

Accessing JSON objects from objects without titles in JQuery

I am receiving this JSON file back from an AJAX call:

[
    {
        "LINKNAME": "Annual Training",
        "HITS": 1
    },
    {
        "LINKNAME": "In Focus Newsletter",
        "HITS": 1
    },
    {
        "LINKNAME": "NITA (secured)",
        "HITS": 1
    },
    {
        "LINKNAME": "Your Current Events",
        "HITS": 1
    },
] 

Here is my AJAX call:

$(document).ready(function(e) {
    $.ajax({
        method: "GET",
        url: url,
    }).done(function(api) {
        console.log(api);
        var obj = JSON.parse(api),
            totRes = Object.keys(obj).length;
        $.each(obj.children, function (index, value) {
            alert(value);
        });
    }).fail(function( jqXHR, textStatus ) {
        alert('Service Catalog: Error loading '+jqXHR+' data. Request fail caused by: '+textStatus);
    });
});

I need to be able to extract the data from the JSON and use it but since the JSON objects aren't gioven a title then I am unsure how to extarpolate the data inside the inner object. Thanks in advance. Please ask if you do not understand my question.

Upvotes: 0

Views: 913

Answers (3)

bcr
bcr

Reputation: 3811

$(document).ready(function(e) {
    $.ajax({
        method: "GET",
        url: url,
    }).done(function(api) {
        if (api && api.length > 0) {
            api.forEach(function (item) {
                console.log(item); // logs whole object
                console.log('item name %s', item.LINKNAME);
                console.log('item hits %s', item.HITS);
            });
        }
    }).fail(function( jqXHR, textStatus ) {
        alert('Service Catalog: Error loading '+jqXHR+' data. Request fail caused by: '+textStatus);
    });
});

You can filter the results to make sure you're only using objects that contain both 'LINKNAME' and 'HITS' pretty easily:

.done(function(api) {
    if (api && api.length > 0) {
        var objs = api.filter(function (item) {
            return item.hasOwnProperty('LINKNAME') && item.hasOwnProperty('HITS');
        });
        objs.forEach(function (item) {
            console.log(item); // logs whole object
            console.log('item name %s', item.LINKNAME);
            console.log('item hits %s', item.HITS);
        });
    }
});

Upvotes: 1

Josh Beam
Josh Beam

Reputation: 19792

Your JSON is just an array of plain objects.

To iterate over an array, you can use various methods. Since you're using jQuery, I'll just suggest $.each:

var arr = JSON.parse(api);

$.each(arr, function(i, obj) {
    // access whatever property you want... obj[LINKNAME] or whatever
});

You can also use Array.prototype.forEach, or even just your basic for loop:

arr.forEach(function(obj) {
    // obj is the current plain object... e.g. { LINKNAME: 'whatever', HITS: 0 }
});

I would also consider paying attention to how you are referring to the objects that you are receiving. While it is true that arrays are objects, and plain objects are objects, I would probably stick to referring to an array as an array, and a plain object as an object. This is because what you are receiving, in the form of JSON, is an array object of plain objects (or more simply, an array of objects).

Calling the array an "object" and referring to it as obj may confuse you when reading through the code quickly (yes, it is a good abstraction for potential extensibility if you end up not always receiving an array, but that's not the case here.)

Also, to once you have access the object in the each loop, you can iterate over the properties of the object if you need to (taken from this answer):

var obj = {
  "a": 1,
  "b": 2,
  "c": 3
};

for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) { 
  // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
    alert("prop: " + prop + " value: " + obj[prop])
  }
}

Upvotes: 1

starikovs
starikovs

Reputation: 3398

First, you can add the setting dataType: 'json' when you send a request. This way you'll have api as javascript array.

Then you'll be able to iterate it via javascript for.

$.ajax({
  method: "GET",
  url: url,
  dataType: "json"
}).done(function(api) {
  for (var i = 0; i < api.length; i++) { 
    var name = api[i]["LINKNAME"],
        hits = api[i]["HITS"];
    // ...
  }
// ...

Upvotes: 1

Related Questions