0

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?

1
  • 1
    If the actual return from the AJAX request is as you show, it is not JSON and will not parse as such. The request should not return such a "list" of objects; it should return an array of objects. At that point, you can access the last one by simply saying json[json.length - 1]. Commented Jul 20, 2015 at 4:27

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

0

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..
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.