Tulika Kansal
Tulika Kansal

Reputation: 57

How to fetch a value from JavaScript array?

I have a JavaScript array and I want to get the value of last name from it. Can anyone tell how to get that from this array example:

var result = [{"FirstName":"paapu","LastName":"gandhi"}];

Upvotes: 0

Views: 40

Answers (2)

Akshay Arora
Akshay Arora

Reputation: 1945

Get the first object.

var obj = result[0];

Refer to the property of the object:

var prop = result[0].FirstName;

If property name comes dynamically, that is, from a variable, use square bracket notation.

var myVar = "FirstName";
var prop = result[0][myVar];

Upvotes: 0

Alberto Nicoletti
Alberto Nicoletti

Reputation: 136

You have an array containing an object, so you have to retrieve the object by doing:

var myObj = result[0]

And then get the LastName property by:

var lastname = myObj.LastName

Upvotes: 1

Related Questions