我有两个JSON对象counties
和ctyIndem
。 counties
对象具有美国各州的所有县,并且ctyIndem
具有按县在该州中支付的赔偿金,但没有支付未付款的那些县。我需要做的是遍历两个JSON,如果ctyIndem
中缺少县名,请添加counties
中的缺少信息。
JS
var counties = [{
FIPS: 1001,
County: "Autauga",
State: "ALABAMA"
}, {
FIPS: 1003,
County: "Baldwin",
State: "ALABAMA"
}, {
FIPS: 1005,
County: "Barbour",
State: "ALABAMA"
}, {
FIPS: 1007,
County: "Bibb",
State: "ALABAMA"
}, {
FIPS: 1009,
County: "Blount",
State: "ALABAMA"
}, {
FIPS: 1011,
County: "Bullock",
State: "ALABAMA"
}];
var ctyIndem = [{
Year: 2015,
State: "ALABAMA",
id: 1001,
County: "Autauga",
Indem: 50
}, {
Year: 2015,
State: "ALABAMA",
id: 1003,
County: "Baldwin",
Indem: 200
}, {
Year: 2015,
State: "ALABAMA",
id: 1005,
County: "Barbour ",
Indem: 1501
}];
counties.forEach(function(a, v) {
if (a.FIPS == ctyIndem[v].id) { //County is present, then is ok
console.log(ctyIndem[v].id);
} else {//County not present, add new info
var temp = [];
temp.push({
Year: ctyIndem[0].Year,
State: a.State,
id: a.FIPS,
County: a.County,
Indem: 0
});
Array.prototype.push.apply(ctyIndem, temp);
}
});
console.log(ctyIndem);
问题是,当我遍历整个数组并到达县FIPS和ID不匹配的地步时,我真的不确定在那做什么。我不断收到Uncaught TypeError:无法读取未定义错误的属性“ id”,因为显然没有匹配项。
谢谢你的帮助。
最佳答案
您的搜索逻辑是错误的。它仅检查ctyIndem
中处于相同索引的元素是否具有匹配的id
。但是两个数组中的索引不匹配。您需要搜索整个阵列。
一种简单的方法是创建一个对象,其键是要搜索的ID。然后,您可以使用a.FIPS
作为索引来查看它是否存在。
var ctyIds = {};
ctyIndem.forEach(function(c) {
ctyIds[c.id] = true;
});
counties.forEach(function(a) {
if (!ctyIds[a.FIPS]) {
ctyIndem.push({
Year: ctyIndem[0].Year,
State: a.State,
id: a.FIPS,
County: a.County,
Indem: 0
});
}
});