Reputation: 15
I'm having difficulty in understanding this, hoping someone can help me out.
So on my site I have an AJAX call that returns all the rows in my table that haven't been read yet (marked with a p
). The data is returned using AJAX and is as follows:
Object {data: Array[22]}
data: Array[22]
0: Object
1: Object
(etc)
Now I need to print out the value at the end of the array (currently 22). But I'm unsure on how to access it (using JavaScript).
Any help would be greatly appreciated! (I can't link to the site as it's local but can provide coding if necessary).
(Yes this is my first job so I'm a little new to this)
Upvotes: 1
Views: 62
Reputation: 7784
Your question is "Show the length of an Array that is contained in an Object"
Having object "object" containing array "data" you can have the length of "data" like this:
var dataLength = object.data.length;
Your second question is "how to print out the data at the end of the array". You say that you have an ajax request in there.
For readability, I assume you are using jquery for ajax, but this doesn't really matter, the important thing is to have your code inside the ajax callback)
$.get(urlToYourServer, function(ajaxReturnedValues){
console.log(ajaxReturnedValues.data[ajaxReturnedValues.data.length-1])
});
As soon as your ajax request comes back, it will "print out the data at the end of the array".
Upvotes: 0
Reputation: 24276
You can do it like this:
var obj = {data: [1, 2, 3, 4, 5]};
var myLastDataElement = obj.data[obj.data.length - 1];
console.log(myLastDataElement);
Here is a demo: http://jqversion.com/#!/6dbEBHA
Upvotes: 1