David David - 2 years ago 76
Javascript Question

Basic javascript / JSON grabbing elements from list

I have a PHP array of data $mainarray that I'm trying to manipulate with javascript.

I did this:

var masterdata = <?php echo json_encode($mainarray); ?>;

To check how that came through, I did this:

alert(JSON.stringify(masterdata, null, 4));

And I got this:


I now just want to loop through every one of those bracketed sets and do something like

if (masterdata[Department] == "Fire" && masterdata[Year] == "2014")
fireamount2014 = masterdata[Amount];

but I think that syntax is nowhere close and I am going mad from lack of basic understanding of how this works.

Answer Source
for (var i in masterdata) {
    if (masterdata[i]['Department'] == 'Fire' && masterdata[i]['Year'] == '2014') {
        fireamount2014 = masterdata[i]['Amount'];

This should work.

EDIT It is also good practice to ensure that the key 'Department', 'Year' and 'Amount' exist first before accessing them by doing something like

if (masterdata[i]['Department'] !== undefined)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download