列表中的基本javascript / JSON抓取元素

时间:2016-10-11 01:41:45

标签: javascript php arrays json

我有一个PHP数组$ mainarray,我试图用javascript操作。

我这样做了:

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

为了检查这是怎么回事,我这样做了:

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

我得到了这个:

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

我现在只想循环遍历这些括号中的每一个并执行类似

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

但我认为语法无处不在,我因为缺乏对其工作原理的基本理解而感到愤怒。

2 个答案:

答案 0 :(得分:0)

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

这应该有用。

修改 确保关键的“部门”,“年”和“年”是一个好习惯。和&#39;金额&#39;在通过执行类似

之类的操作访问它们之前首先存在
if (masterdata[i]['Department'] !== undefined)

答案 1 :(得分:0)

您可以使用Array.prototype.reduce总结每年的消防金额,并将其作为按年份索引的对象传回。

const data = [{
  "Department": "Fire",
  "Year": "2014",
  "Amount": "311.3"
}, {
  "Department": "Police",
  "Year": "2014",
  "Amount": "622.3"
}, {
  "Department": "Vehicles",
  "Year": "2014",
  "Amount": "100.9"
}, {
  "Department": "Vehicles",
  "Year": "2015",
  "Amount": "100.9"
}]

console.log(
  data.reduce((acc, item) => {
    // set the default for the year
    if (!acc['FireAmount_' + item.Year]) {
      acc['FireAmount_' + item.Year] = 0
    }
    // increment the new amount on the the stored FireAmount
    acc['FireAmount_' + item.Year] += Number(item.Amount)
    return acc
  }, {})
)