LauraNMS
LauraNMS

Reputation: 2863

display children on json object

I have a php file that returns this json (I've validated it):

{"images":{"2":"building.jpg","3":"campus.jpg","4":"grads.jpg","5":"trio.jpg"},"videos":[]} 

In jquery, how do I return the number of children of 'images'? WhenI use:

$.post('php/file.php', {variable: variable}, function(returnedData) {
        console.log(returnedData);
        var obj = jQuery.parseJSON( returnedData );
        console.log(obj.images.length);

    });

I get 'undefined'.

It is the way I'm building the json in php?

 $variable= $_POST['variable'];
$imgdir    = '../' . $variable. '/img';
$weeds = array('.', '..'); 
$images = array_diff(scandir($imgdir), $weeds); 
$viddir = '../' . $school . "/vid";
$vids = array_diff(scandir($viddir), $weeds); 
$data = array();
$data['images'] = $images;
$data['videos'] = $vids;
echo json_encode($data);

Upvotes: 0

Views: 95

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

That happens because obj.images is not Array, you can get length like so

var returnedData = {"images":{"2":"building.jpg","3":"campus.jpg","4":"grads.jpg","5":"trio.jpg"},"videos":[]};

console.log(Object.keys(returnedData.images).length);

Object.keys() - returns an array of a given object's own enumerable properties

or you can use for..in, like so

 var returnedData = {"images":{"2":"building.jpg","3":"campus.jpg","4":"grads.jpg","5":"trio.jpg"},"videos":[]};

var count = 0;
for (var i in returnedData.images) {
  if (returnedData.images.hasOwnProperty(i)) {
     count += 1;  
  }
}

console.log(count);

Upvotes: 1

1111161171159459134
1111161171159459134

Reputation: 1215

Why not using $.getJSON():

$.getJSON('php/file.php', {variable: variable}, function(returnedData) {
    console.log(returnedData);
    console.log(Object.keys(returnedData.images).length);
});

Upvotes: 0

Related Questions