我有兩個JSON對象counties
和ctyIndem
。 counties
對象擁有美國所有州,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錯誤,因爲顯然沒有匹配。 感謝您的幫助。
看起來您的邏輯看起來是錯的。你期望兩個陣列中的縣都有相同的索引。你需要搜索整個'ctyIndem'數組,看看是否有一個匹配的ID。 – Barmar
你爲什麼使用'Array.prototype.push.apply'?只需編寫'ctyIndem.push({...})' – Barmar