简体   繁体   English

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

[英]Undefined issue when comparing two JSON files

test.json test.json

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

app.js 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 的HTML

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

I need to check the scodes of callplans.json and test.json, if any common values are available then I need to enable a div in HTML. 我需要检查callplans.json和test.json的代码,如果有任何常用值,那么我需要在HTML中启用div。 But I'm getting undefined in the console for this code - console.log($scope.testing[t].Scode); 但是我在控制台中对于这段代码没有定义-console.log($ scope.testing [t] .Scode); and getting the correct values as 2 for $scope.testing.length; 并将$ scope.testing.length的正确值设为2;

Any help would be appreciated 任何帮助,将不胜感激

Note: I'm not attaching the other JSON files and code because for this functionality those are not required. 注意:我没有附加其他JSON文件和代码,因为对于此功能,这些不是必需的。

Since the format of your data is weird, that would have to be: 由于您的数据格式很奇怪,因此必须是:

console.log($scope.testing[t][1].Scode);

See also the snippet below. 另请参见下面的代码段。

 const data = { "discountPriceValues": [ [{ "Price": "0.0" }, { "Scode": "S0375102" }], [{ "Price": "2.0" }, { "Scode": "s0779548" }] ], "isEmployeeOJ": "Y" }; for (var t = 0; t < data.discountPriceValues.length; t++) { console.log(data.discountPriceValues[t][1].Scode); } 

I saw that your json object contains nested arrays. 我看到您的json对象包含嵌套数组。

As I said in comments, just change to $scope.testing[t][1].Scode , because you have nested arrays. 正如我在评论中所说,只需更改为$scope.testing[t][1].Scode ,因为您已嵌套了数组。

I suggest to use filter method in order to check if you have common values. 我建议使用filter方法以检查您是否有共同的价值观。

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 的HTML

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM