javascript - Accessing JSON objects from objects without titles in JQuery -
i receiving json file 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 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 able extract data json , use since json objects aren't gioven title unsure how extarpolate data inside inner object. in advance. please ask if not understand question.
your json array of plain objects.
to iterate on array, can use various methods. since you're using jquery, i'll suggest $.each
:
var arr = json.parse(api); $.each(arr, function(i, obj) { // access whatever property want... obj[linkname] or whatever });
you can use array.prototype.foreach
, or basic for
loop:
arr.foreach(function(obj) { // obj current plain object... e.g. { linkname: 'whatever', hits: 0 } });
i consider paying attention how referring objects receiving. while true arrays objects, , plain objects objects, stick referring array array, , plain object object. because receiving, in form of json, array object of plain objects (or more simply, array of objects).
calling array "object" , referring obj
may confuse when reading through code (yes, abstraction potential extensibility if end not receiving array, that's not case here.)
also, once have access object in each
loop, can iterate on properties of object if need (taken answer):
var obj = { "a": 1, "b": 2, "c": 3 }; (var prop in obj) { if (obj.hasownproperty(prop)) { // or if (object.prototype.hasownproperty.call(obj,prop)) safety... alert("prop: " + prop + " value: " + obj[prop]) } }
Comments
Post a Comment