3

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.

user2770956
  • 75
  • 2
  • 11

3 Answers3

3

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);
});
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

As you have the name of the property in the object you want to retrieve you can use bracket notation. you can also simplify your code because of this:

var id = 301;

//$.getJSON("path/to/file.json", function(json) {
  // response data from AJAX request:
  var json = {
    '301': {
      banos: 2
    },
    '302': {
      banos: 3
    },
    '303': {
      banos: 4
    },
    '304': {
      banos: 5
    },
  };

  var item = json[id];
  console.log(item);
//});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0
$.each(items,function(n,value){
    if(n==301)
        alert(value);
});
dakab
  • 5,379
  • 9
  • 43
  • 67
hackfox code
  • 509
  • 4
  • 4
  • 1
    Please provide more details to your answer as this post has been found in low quality post. Code only and 'try this' answers are discouraged as it doesn't provide any searchable content and why people should 'try this'. – Paritosh Sep 03 '16 at 09:54