user2322791 user2322791 - 1 year ago 71
Javascript Question

Accessing the properties of an object without knowing the names of those properties not working

I have index.php with:

These php lines

$sql = "SELECT * FROM voedingsmiddelen";
$result = mysqli_query($conn, $sql);


On the same page i have this code where extract data from table and put it in an array.

var array = <?php echo json_encode( mysqli_fetch_all( $result, MYSQLI_ASSOC ) ) ?>;
var arraytype = typeof array;
alert('type: '+arraytype);

var i=0;
for(key in array) {
alert('for loop working');
if(data.hasOwnProperty(key)) {
var value = data[key];
alert(value);
} else {
alert('has no property');
}
}


i only get one alert saying 'type: object'. So the "gettype" is working. But the other alerts are not displaying. What am i doing wrong?

Answer Source

hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument here.So try this

for (var i=0; i<array.length; i++) {
    alert('for loop working');
    if(array.hasOwnProperty(i)) {
        var value = i;
        alert(value);
    } else {
        alert('has no property');
    }
}

or in your case this:

var i=0;
for(key in array) {
    alert('for loop working');
    if(array.hasOwnProperty(key)) {
        var value = key;
        alert(value);
    } else {
        alert('has no property');
    }
}  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download