cubanGuy cubanGuy - 2 months ago 13
JSON Question

Compare two JSON object and find missing values using javascript

I have two JSON objects

counties
, and
ctyIndem
. The
counties
object has all the counties in a US State, and
ctyIndem
has the indemnities paid in that State by county, but not those counties which no payment has been made. What I need to do is to iterate through both JSON, and if a county is missing from
ctyIndem
add the missing info from
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);


The issue is when I iterate throught the array and gets to the point when the county FIPS and id don't match, I really not sure what to do there. I keep getting a Uncaught TypeError: Cannot read property 'id' of undefined error, because obviously there is no match.
Thanks for any help.

Answer

Your searching logic is wrong. It only checks whether the element at the same index in ctyIndem has the matching id. But the indexes in the two arrays don't match. You need to search the entire array.

A simple way to do this is to create an object whose keys are the IDs you want to search for. Then you can just use a.FIPS as an index to see if it exists.

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
        });
    }
});