2016-09-23 120 views
0

我有两个JSON对象countiesctyIndemcounties对象拥有美国所有州,ctyIndem有按县支付的赔款,但不包括那些没有付款的县。我需要做的是遍历两个JSON,并且如果从ctyIndem中缺少一个县,请从counties中添加缺失的信息。比较两个JSON对象并使用javascript查找缺失值

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

的问题是,当我重复阵列throught和到达点时,县FIPS和身份证不相符,我真的不知道该怎么办那里。我不断收到Uncaught TypeError:无法读取属性'id'的undefined错误,因为显然没有匹配。 感谢您的帮助。

+0

看起来您的逻辑看起来是错的。你期望两个阵列中的县都有相同的索引。你需要搜索整个'ctyIndem'数组,看看是否有一个匹配的ID。 – Barmar

+0

你为什么使用'Array.prototype.push.apply'?只需编写'ctyIndem.push({...})' – Barmar

回答

1

你搜索的逻辑是错误的。它只检查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 
     }); 
    } 
}); 
1

在你的循环,你首先需要检查ctyIndem[v]存在

// v--- check that it exists 
if (ctyIndem[v] && a.FIPS == ctyIndem[v].id) { //County is present, then is ok 
    console.log(ctyIndem[v].id); 
} else {//County not present, add new info 
1

首先用ctyIndem创建一个扁平数组。使用Array.filter方法,您可以生成ID列表中缺少的县数组。然后为每个缺失的县推入一个新对象:

var indemIds = ctyIndem.map(function (c) { return c.id }); 

    var missingFromIndem = counties.filter(function (cnty) { 
     return indemIds.indexOf(cnty.FIPS) === -1; 
    }); 

    missingFromIndem.forEach(function (cnty) { 
     ctyIndem.push({ 
     id: cnty.FIPS, 
     State: cnty.State, 
     County: cnty.County 
     }); 
    });