user2770956 user2770956 - 3 months ago 9
jQuery Question

Get object from JSON with jQuery

I'm trying to query a JSON file in my own server using

$.getJSON
and then cycling inside the objects. No problem so far, then i have an ID which is the name of the object i want to return, but can't seem to get it right:

var id = 301;
var url = "path/to/file.json";
$.getJSON( url, function( json ) {
var items = [];
items = json;
for (var i = 0; i < items.length; i++) {
var item = items[i];
console.log(item);
}
});


This prints the following in the console:

console.log of all the objects in json

Now let's say i want return only the object
==
to
id
so then i can refer to it like
item.banos
,
item.dorms
etc.

My first approach was something like

console.log(json.Object.key('301'));


Which didn't work

Any help would be very much appreciated.

Answer

It seems like your response is wrapped in an array with one element.


You can access object properties dynamically via square brackets:

var id = 301;
var url = "path/to/file.json";
$.getJSON(url, function(json) {
    console.log(json[0][id].banos);
});
Comments