1

I'm getting this JSON object from a php page:

{
    "0": "8:00",
    "1": "8:30",
    "2": "9:00",
    "3": "9:30",
    "4": "10:00",
    "5": "10:30",
    "6": "11:00",
    "7": "11:30",
    "8": "12:00",
    "9": "12:30",
    "10": "13:00",
    "11": "13:30",
    "12": "14:00",
    "13": "14:30",
    "14": "15:00",
    "15": "15:30",
    "18": "17:00",
    "19": "17:30",
    "20": "18:00",
    "21": "18:30",
    "22": "19:00",
    "23": "19:30"
}

and I want to run through it and print its values. Right now I can print the whole thing to the screen (exactly as is pasted above) using Json.stringify, but I want to print only the values, without the keys. If I try to print the result to the console like

console.log(results);

All I get is

Object {hours: Object}

I'm quite new at making JSON calls and manipulating responses, so I can't quite do what I need just looking at the other questions I found. Thanks

edit: The result I'm expecting is

8:00
9:00
etc

on a div.

A.Draug
  • 43
  • 7

4 Answers4

2

you have to loop through the object assuming results is the object

for(var hours in results){
     console.log(results[hours]);
}
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
Lunny
  • 852
  • 1
  • 10
  • 23
2

You can use for...of loop:

for(var hours of results){
     console.log(hours);
}
Ivan Matveev
  • 225
  • 1
  • 8
0

To fetch the values from an object and discard keys, you want to chain Object.keys with Array.prototype.map like so:

var data = { "0": "8:00", "1": "8:30", "2": "9:00", "3": "9:30", "4": "10:00", "5": "10:30", "6": "11:00", "7": "11:30", "8": "12:00", "9": "12:30", "10": "13:00", "11": "13:30", "12": "14:00", "13": "14:30", "14": "15:00", "15": "15:30", "18": "17:00", "19": "17:30", "20": "18:00", "21": "18:30", "22": "19:00", "23": "19:30" };
var result = Object.keys(data).map(function (key) {
  return data[key];
});
console.log(result);
ssube
  • 47,010
  • 7
  • 103
  • 140
0

It's not necessary in your example since you're getting the JSON from a page but to avoid potential issues in the future you should always do a hasOwnProperty check to make sure you're only getting properties of the JSON object and no inherited properties:

for(key in data)
{
    if(data.hasOwnProperty(key))
    {
        console.log(data[key]);
    }
}
IMTheNachoMan
  • 5,343
  • 5
  • 40
  • 89