我只是在学习如何从 JSON 文件中检索数据并将其充分利用,并且我发现 for..in 循环很有帮助,但我知道我在从 JSON 中获取价值方面做得太多了文件。
这是我的 JSON - 它不必以这种方式构造。
var dollars = { "zipcodes": {
"one": {
"donors": {
"donor_profile1": {
"name": "Doug Smith",
"address" : "123 main st",
"gifts":{
"gift0": {
"recipient":"Greg",
"amount": 45000,
"date":"7/1/2013"
},
"gift1":{
"recipient":"Greg",
"amount": 6000,
"date":"7/1/2013"
},
"gift2":{
"recipient":"Marty",
"amount": 2000,
"date":"7/1/2013"
}
}
},
"donor_profile2": {
"name": "Bert Bernard",
"address" : "123 South st",
"gifts": {
"gift0": {
"recipient":"Greg",
"amount": 1200,
"date":"7/4/2013"
},
"gift1":{
"recipient":"Marty",
"amount": 400,
"date":"7/9/2013"
},
"gift2":{
"recipient":"Marty",
"amount": 510,
"date":"7/21/2013"
}
}
}
}
}
我想把每个捐赠者的礼物都收集起来,然后加起来。我编写了这个程序来获取所有的礼物金额,但它们并没有被捐赠者分开。关于如何使这个更清洁的任何建议?
var info = dollars.zipcodes.one;
function buildSum(){
for (var key in info){
if (info.hasOwnProperty(key)) {
var person = info[key];
};
for (prop in person) {
if(person.hasOwnProperty(prop)){
var name = person[prop].gifts;
};
for(value in name){
if(name.hasOwnProperty(value)){
var money = name[value].amount;
};
}
}
}
}
buildSum();