简体   繁体   中英

How can I access properties inside objects inside other objects in javascript

I am trying to access the text property of each object stored in an array. The array is a value of another property, results, inside an object.

I retrieve the object from a server using jQuery, like this.

       $.ajax({
       url: "https://api.parse.com/1/classes/chats",
       cache: false,
       type: 'get',
       async: false,
       success: function(data){
            console.log(data);
        }
       });

The log statement at the end is to see what I am receiving. Naturally this is where I need to be doing something, but I can't seem to crack the code. So, I have an object with the result property and Array value. The array is an array of objects, each with their own properties. I'm just a bit confused on how to get what I need. Perhaps a gentle nudge in the right direction?

Object {results: Array[10]} //object returned

results: Array[10] //value is an array of objects

0: Object           // object '0' expanded...

createdAt: "2013-10-15T19:13:43.576Z"<br><br>
objectId: "uzGerloXA7"
text: "RoboChat: I'm sorry Dave, I can't allow you to do that." // I need this!
updatedAt: "2013-10-15T19:13:43.576Z"
username: "RoboChat"

1:Object   // and I need it for each of these objects.
2:Object
3:Object
etc...
9:Object   //this is the last object.

You want

data.results[0].text

[] will let you get an individual element of an array

. will let you get properties of any object.

You'll probably want a loop:

for (var i = 0; i < data.results.length; ++i) {
    console.log(data.results[i].text);
}

Just specify the array index followed by the property name:

data.results[0].propName;

To iterate, you could do:

//Iterate the array of objects
for (var i = 0; i < data.results.length; i++) {
    //Iterate over the keys of a specified object
    for (var key in data.results[i]) {
        if (data.results[i].hasOwnProperty(key))
            console.log(data.results[i][key]);
    }
}

you could do some iteration like :

   var allText = [];
    $.each(data.results,function(i,obj){
      allText.push(obj.text);
    });

and all texts are stored in allText ah and its jquery moe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM