Tcmxc
Tcmxc

Reputation: 491

How do I return object values in jquery

I'm not sure if its actually a object but that's what it says in the console.

I have a object that lookes like this

[{"id_no":"6798","name":"Annunication Of The Bvm","address1":"27335 N 8Th St "},
{"id_no":"6815","name":"Francis Of Paola  ","address1":"21229 Conselyea St "}]

How do I display the value of "name" if a for loop. This is what I tried with no success

  success:function(data){

                console.log(data);
                var pardata = JSON.stringify(data);

                for(name in pardata) {
                    if(pardata.hasOwnProperty(name)) {
                        var value = pardata[name];
                         alert(value);
                         console.log(value);
                    }
                }

           }

Upvotes: 0

Views: 734

Answers (2)

Karthikeyan Sekar
Karthikeyan Sekar

Reputation: 333

Demo

var val=[{"id_no":"6798","name":"Annunication Of The Bvm","address1":"27335 N 8Th St "},
{"id_no":"6815","name":"Francis Of Paola  ","address1":"21229 Conselyea St "}]
//Method 1
$('button').click(function(){
  $.each(val,function(i,e){
    $('div').append('<p>'+e.name+'</p>');     
  });  
})
//Method 2
$('button').click(function(){
  $pList='';
  $.each(val,function(i,e){
    $pList+='<p>'+e.name+'</p>';     
  });
  $('div').html($pList);
})

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

You have an Array of objects - and an Array is an object, so yeah. You have to iterate the array and then display the property:

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

Your issue was with using for...in (on a string version of your array) - which is used to iterate the properties of an object. name was being assigned an index of the array - so data[name] was actually selecting an object at that index. data[name].name would've probably worked - but that's not the correct way to iterate an array.

Upvotes: 2

Related Questions