NewUser
NewUser

Reputation: 13323

jQuery get data from jQuery object

I am using ajax to get the data from the database. After getting data from table I am doing json_encode to get the data in json format. After that I am doing parseJSON to show the data in js.

when I am getting the data in json I just did

data = $.parseJSON(data);

console.log(data);

I got the data like this jQuery object.

enter image description here

From here I want to get the values of firstname.

I tried console.log(data.first_name); but it not worked. It is showing undefined in the console tab. So can someone tell me how to get the first_name value here

Upvotes: 0

Views: 97

Answers (4)

Kelsadita
Kelsadita

Reputation: 1038

It looks like data is array of objects you have to iterate over this array and get the first_name attribute of each object in it as follows,

data = $.parseJSON(data);
data.forEach(function(item){
  console.log(item.first_name);
})

Upvotes: 0

Girish
Girish

Reputation: 12127

jquery provide $.each() function to iterate object or array, see below sample code

data = $.parseJSON(data);
$.each(data, function(index, object){
  console.log(object.first_name);
})

Upvotes: 0

apsdehal
apsdehal

Reputation: 845

You have been returned an array of objects. Iterate through all of them using:

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

Upvotes: 0

A.B
A.B

Reputation: 20445

Your data is array of objects and has data on indexes 0,1,2 so on so you need

try

console.log(data[0].first_name);

you can also loop through them

for(var a=0;a<data.length;a++) {
    console.log(data[a].first_name);
}

Upvotes: 1

Related Questions