David David - 1 month ago 7
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:

{
"Department":"Fire",
"Year":"2014",
"Amount":"311.3"
},
{
"Department":"Police",
"Year":"2014",
"Amount":"622.3"
},
{
"Department":"Vehicles",
"Year":"2014",
"Amount":"100.9"
}
...


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
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)
Comments