Clay Banks
Clay Banks

Reputation: 4581

Retrieve Last Object in List of JSON Objects

I have a list of JSON objects returned from an AJAX request:

Object {id: 1, name: "Ben Roethlisberger"}
Object {id: 2, name: "Antonio Brown"}
Object {id: 3, name: "Le'Veon Bell"}

I can access name from a single object with the following

e.data.name

Is there any way I can retrieve the very last object from the list, and grab that object's name?

Upvotes: 0

Views: 135

Answers (3)

gor181
gor181

Reputation: 2068

Just use array.pop() and then access the object properties as needed.

So...

var list = [{ a: '1'}, {b: '2'}];
var lastObject = list.pop();

if(lastObject) {
 //use object..
}

Upvotes: 0

Giau Huynh
Giau Huynh

Reputation: 300

Is there your json data:

var data = [ {id: 1, name: "Ben Roethlisberger"}
, {id: 2, name: "Antonio Brown"},
{id: 3, name: "Le'Veon Bell"}];

You can access name from a single object with the following, with index start by 0:

data[index].name

Each object has length, list start index by zero, you can access last object in list by:

data[data.length-1].name

Here is example: http://jsfiddle.net/oht1mke9/

Upvotes: 1

monkey
monkey

Reputation: 1279

If your response is:

var response = [
  {id: 1, name: "Ben Roethlisberger"},
  {id: 2, name: "Antonio Brown"},
  {id: 3, name: "Le'Veon Bell"}
]

You can do:

var lastObjectName = response[response.length - 1].name;

for (var i = 0; i < response.length; i++) {
   var name = response[i].name;
}

Upvotes: 1

Related Questions