Wednesday 29 November 2017

How to iterate the objects in array in jQuery?

itemprop="text">

I have a JSON
object:




[{

name:'bhavani',
age:'19',
gender:'Female'
},{

name:'bhavani',
age:'19',

gender:'Female'
},{

name:'bhavani',

age:'19',
gender:'Female'
}, {
// and so
on
}]


Now i
need to access the name in each object in this array in a JSP
page. I am unable to do it. Can anyone solve this problem for me
please.



Answer





To loop over an array or an
object's properties you can use the $.each
function.



Fiddle: href="http://jsfiddle.net/AtheistP3ace/ohswrnmn/"
rel="nofollow">http://jsfiddle.net/AtheistP3ace/ohswrnmn/



var
data = [{
name: 'bhavani',
age: '19',
gender:
'Female'
}, {
name: 'bhavani',

age:
'19',
gender: 'Female'
}, {
name: 'bhavani',

age: '19',
gender: 'Female'
}, ];

var $test =
$('#test');
$.each(data,

function (index, value)
{
$test.append(value.name + ' ');

}
);


jQuery
docs: rel="nofollow">http://api.jquery.com/jquery.each/



Example
looping over array and each objects
properties:




Fiddle: href="http://jsfiddle.net/AtheistP3ace/ohswrnmn/1/"
rel="nofollow">http://jsfiddle.net/AtheistP3ace/ohswrnmn/1/



var
data = [{
name: 'bhavani',
age: '19',
gender:
'Female'
}, {
name: 'bhavani',
age: '19',

gender: 'Female'

}, {
name: 'bhavani',
age:
'19',
gender: 'Female'
}, ];

var $test =
$('#test');
$.each(data,
function (index, value) {

$test.append(index + ': ');

$.each(value,
function
(index2, value2) {
$test.append(value2 + ' ');
}

);
$test.append(' - ');

}
);

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...