比较两个JSON对象并使用javascript查找缺少的值
我有两个JSON对象比较两个JSON对象并使用javascript查找缺少的值,javascript,json,Javascript,Json,我有两个JSON对象country,和ctyIndem。countries对象包含美国各州的所有县,ctyIndem在该州按县支付赔偿金,但不包括未支付赔偿金的县。我需要做的是迭代两个JSON,如果ctyIndem中缺少一个县,则添加县中缺少的信息 JS 问题是,当我遍历数组并到达县FIP和id不匹配的点时,我真的不知道该怎么做。我一直收到一个未捕获的类型错误:无法读取未定义错误的属性“id”,因为显然没有匹配项。 感谢您的帮助。在您的循环中,您首先需要检查ctyIndem[v]是否存在 //
country
,和ctyIndem
。countries
对象包含美国各州的所有县,ctyIndem
在该州按县支付赔偿金,但不包括未支付赔偿金的县。我需要做的是迭代两个JSON,如果ctyIndem
中缺少一个县,则添加县中缺少的信息
JS
问题是,当我遍历数组并到达县FIP和id不匹配的点时,我真的不知道该怎么做。我一直收到一个未捕获的类型错误:无法读取未定义错误的属性“id”,因为显然没有匹配项。
感谢您的帮助。在您的循环中,您首先需要检查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
在循环中,首先需要检查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
你的搜索逻辑是错误的。它只检查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
});
}
});
你的搜索逻辑是错误的。它只检查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
});
}
});
首先创建一个平面阵列,仅使用ctyIndem中的ID。使用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
});
});
首先创建一个平面阵列,仅使用ctyIndem中的ID。使用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
});
});
看来你的逻辑全错了。您希望两个县在两个数组中具有相同的索引。您需要搜索整个ctyIndem
数组,查看是否有一个ID匹配的数组。为什么要使用array.prototype.push.apply
?只要写ctyIndem.push({…})
你的逻辑似乎全错了。您希望两个县在两个数组中具有相同的索引。您需要搜索整个ctyIndem
数组,查看是否有一个ID匹配的数组。为什么要使用array.prototype.push.apply
?只需编写ctyIndem.push({…})