David David - 5 months ago 22
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.

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)