Two JSON objects, counties
and ctyIndem
, are at hand. The counties
object contains all the counties in a specific US State, while ctyIndem
holds information about indemnities paid in that State by county, excluding those with no payments made. My task is to iterate through both JSON objects, and if a county is missing from ctyIndem
, I must add the missing information from counties
.
JavaScript Code:
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) {
console.log(ctyIndem[v].id);
} else {
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);
An issue arises when iterating through the arrays and encountering a point where the county FIPS and id do not match. I am unsure of what action to take in such instances, resulting in a Uncaught TypeError: Cannot read property 'id' of undefined error since there is no match. Thank you for any assistance.