Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Ajax get returns an array with objects with multiple values

Hey All,

I'm using ajax to get a bunch of messages. The get call works fine, but I don't know how to get the specific key values from the object in the array. I've used console.log to get the actual array which is here:

Object {results: Array[10]}
results: Array[10]
0: Object
createdAt: "2014-05-22T21:42:03.514Z"
objectId: "3N2xHfYBMh"
text: "What is your sign?"
updatedAt: "2014-05-22T21:42:03.514Z"
username: "Luffy"
__proto__: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
length: 10

I'm trying to get the username, text, and createdAt fields for each of the objects.

Here is the what I have so far

var myChat = function() {
    $.ajax({
        url: "https://api.parse.com/1/classes/chats?order=-createdAt",
        type: "Get",
        datatype:"JSON",
        contentType: "application/json",
        data: JSON.stringify({
           text : "value",
           order: "-createdAt"
           username: "value"
    }),     
        error : function(data){console.log("error:" + data)
    },
        success: function(response){
        $("li").remove();
        response.forEach(function(data) {
        $(".messages").append("<li>"+username+":"+text+"</li>") 
        })  
        }
})
}

1 Answer

You can get those properties for each object using the dot notation:

data.username; // grabs the username
data.text; // grabs the text
data.createdAt; // grabs createdAt

So the success function could look like this:

success: function(response){
   $("li").remove();
   response.forEach(function(data) {
      $(".messages").append("<li>" + data.username + ":" + data.text + "</li>");
   });
}