gpt4 book ai didi

javascript - 使用 for..in 循环访问 JSON 数据

转载 作者:行者123 更新时间:2023-11-29 10:46:51 24 4
gpt4 key购买 nike

我刚刚学习如何从 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();

最佳答案

如评论部分所述,您可能应该在适当的地方使用数组。所以您的 JSON 数据可能如下所示:

var dollars = {
"zipcodes": {
"one": {
"donors": [{
"name": "Doug Smith",
"address": "123 main st",
"gifts": [{
"recipient": "Greg",
"amount": 45000,
"date": "7/1/2013"
}, {
"recipient": "Greg",
"amount": 6000,
"date": "7/1/2013"
}, {
"recipient": "Marty",
"amount": 2000,
"date": "7/1/2013"
}]
}, {
"name": "Bert Bernard",
"address": "123 South st",
"gifts": [{
"recipient": "Greg",
"amount": 1200,
"date": "7/4/2013"
}, {
"recipient": "Marty",
"amount": 400,
"date": "7/9/2013"
}, {
"recipient": "Marty",
"amount": 510,
"date": "7/21/2013"
}]
}]
}
}
};

这使您能够使用 Array.prototype 的一些功能。就我而言,我使用 Array.mapArray.reduce , 生成一个数组,其中包含每个捐赠者的捐赠总额:

//first map: turn the array of donors in an array of gift array
var res = dollars.zipcodes.one.donors.map(function (item) {

//second map: turn each gift array in an array of amount
return item.gifts.map(function (item) {
return item.amount;

//use reduce to sum up the amount in each array
}).reduce(function (a, b) {
return a + b;
});
});

console.log(res); //[53000, 2110]

FIDDLE

关于javascript - 使用 for..in 循环访问 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com