2016-09-23 116 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 
     }); 
    });