javascript - 比较两个 JSON 文件时出现未定义问题

标签 javascript html angularjs json

test.json

{"discountPriceValues":[[{"Price":"0.0"},{"Scode":"S0375102"}],[{"Price":"2.0"},{"Scode":"s0779548"}]],"isEmployeeOJ":"Y"}

app.js

var test = $http.get("data/test.json").then(function (response5) {
  $scope.testing = response5.data;
  return response5;
});
test.then(function(testing){
    $scope.testing = testing.data.discountPriceValues;
}); 

for(var x = 0; x < $scope.callplanList.length; x++){
  for(var t = 0; t < $scope.testing.length; t++ ){
                        console.log($scope.testing[t].Scode);
                            if($scope.callplanList[x].s_code == $scope.testing[t].Scode){
                                console.log($scope.testing[t]);
                            }
                    }
}

HTML

<div class="description">
<p>Test</p>
</div>

我需要检查 callplans.json 和 test.json 的代码,如果有任何通用值可用,那么我需要在 HTML 中启用 div。但我在控制台中未定义此代码 - console.log($scope.testing[t].Scode);并为 $scope.testing.length 获取正确的值 2;

如有任何帮助,我们将不胜感激

注意:我没有附加其他 JSON 文件和代码,因为对于此功能来说,这些不是必需的。

最佳答案

我发现您的 json 对象包含嵌套数组。

正如我在评论中所说,只需更改为 $scope.testing[t][1].Scode,因为您有嵌套数组。

我建议使用filter方法来检查你们是否有共同的值(value)观。

let callplanListCodes = $scope.callplanList.map(a=>a[1].Scode);
let testingCodes = $scope.testing.map(a=>a[1].s_code;
$scope.hasCommon = callplanListCodes .filter((n) => testingCodes .includes(n))

HTML

<div ng-if="hasCommon" class="description">
  <p>Test</p>
</div>

关于javascript - 比较两个 JSON 文件时出现未定义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48205020/

相关文章:

javascript - 链接未显示在 D3 v4 强制布局中

javascript - 使用 AJAX 将数据从 PHP 返回到 JavaScript - 数据类型错误?

javascript - 表中的 ng-repeat datepickers 提示 'missing instance data' 错误

javascript - Spring POST 接收具有空值的对象

javascript - Satellizer 提供商在 Chrome 浏览器、AngularJS 中登录

php - PHP 中的 Tab 键操作?

javascript - PreventDefault 不阻止使用 Alt 修饰符的键

javascript - 如何通过鼠标滚动按钮左右滚动

javascript - reCAPTCHA 停止工作 - 加密无效

jquery - 多选的返回值