-1

I get a json response from a ajax request, the response is the follow:

{
    1: {
        id: 1,
        title: "departure1 - arrival1",
        start: "2018-01-01 12:01:00"
    },
    2: {
       id: 2,
       title: "departure2 - arrival2",
       start: "2018-02-01 12:02:00"
    }
}

I try to index that int the follow mode, but obviously doesn't work becous is only one object, but i hope thate with this i can explain better what i want do:

var xhr = new XMLHttpRequest();
xhr.onload = function () {
    if(xhr.status === 200) {
        var responseObject = JSON.parse(xhr.responseText);
       for(var i=0; i<responseObject.length; i++) {
           console.log(responseObject[0]);
       }
    }
};
var url = 'http://localhost:8081/get_transfer_booked';
xhr.open('GET', url, true);
xhr.send(null);
mastrobirraio
  • 135
  • 1
  • 9

2 Answers2

1

Javascript key-value objects don't accept numbers as a key.

You can loop through its keys:

var responseObject = {
  '1': {
    id: 1,
    title: "departure1 - arrival1",
    start: "2018-01-01 12:01:00"
  },
  '2': {
    id: 2,
    title: "departure2 - arrival2",
    start: "2018-02-01 12:02:00"
  }
}

var keys = Object.keys(responseObject);
for (var i = 0; i < keys.length; i++) {
  console.log(responseObject[keys[i]]);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or, you can loop through its values:

var responseObject = {
  '1': {
    id: 1,
    title: "departure1 - arrival1",
    start: "2018-01-01 12:01:00"
  },
  '2': {
    id: 2,
    title: "departure2 - arrival2",
    start: "2018-02-01 12:02:00"
  }
}

var values = Object.values(responseObject);
for (var i = 0; i < values.length; i++) {
  console.log(values[i]);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
0
  var xhr = new XMLHttpRequest();
xhr.onload = function () {
    if(xhr.status === 200) {
        var responseObject = JSON.parse(xhr.responseText);
        Object.keys(responseObject).forEach((res)=>{
            console.log(responseObject[res])
        })
    }
};
var url = 'http://localhost:8081/get_transfer_booked';
xhr.open('GET', url, true);
xhr.send(null);

are you looking for something like this one

Saikat Hajra
  • 670
  • 3
  • 12