0

I'm using this:

function httpGet(theUrl)
{
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

var responseText=httpGet('https://xxxxxxxxxxxxxxxxxxxxxxxxx');

to get JSON response as fallow:

{
    "response": {
    "status": 1,
    "httpStatus": 200,
    "data": {
      "40": {
        "AccountNote": {
          "id": "40",
          "type": "azx",
          "account_id": "1111",
          "created": "2015-02-11 11:12:03",
          "note": "test"
        }
      },
      "42": {
        "AccountNote": {
          "id": "42",
          "type": "azx",
          "account_id": "1111",
          "created": "2015-02-11 11:27:56",
          "note": "zzzzzzz"
        }
      }
    },
    "errors": [],
    "errorMessage": null
  }
}

I want to get values of all note parameters. I know i can do that using this:

var obj=JSON.parse(responseText);
console.log(obj.response.data[40].AccountNote.note+' '+obj.response.data[42].AccountNote.note);

I don't know how many data in response.data will be. I don't know their names either (in these example '40' and '42). So i tried something like this:

var text='';
for(var i=0;i<obj.response.data.length;i++)
    text+=obj.response.data[i].AccountNote.note;

but this of course doesn't work. How i can do the trick?

traffic
  • 67
  • 1
  • 1
  • 5

1 Answers1

-1

You can iterate through them using for loop like so:

var text='';
for(var i in obj.response.data)
{
    text += obj.response.data[i].AccountNote.note;
}

Variable i is index of element in the array obj.response.data so you don't have to worry about random indexes anymore.

krzysiej
  • 889
  • 9
  • 22
  • Problems like _"How to iterate over objects"_ have been answered on SO plenty of times already. I'd recommend close-voting as duplicate, instead of answering such questions, since the OP should've searched a bit before asking on SO. – Cerbrus Feb 11 '15 at 13:13
  • @traffic check this: http://jsfiddle.net/54peq372/ – Ivan Sivak Feb 11 '15 at 13:20