我有两个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