Как проверить наличие ключа в объекте с помощью AngularJS?
Опубликовано: 25 Февраля, 2022
Дан объект, содержащий пару (ключ, значение), и задача состоит в том, чтобы проверить, существует ли ключ в объекте или нет, используя AngularJS.
Подход: подход заключается в использовании оператора in, чтобы проверить, существует ли ключ в объекте или нет. В первом примере вводится ключ «Prop_1», и он существует в объекте. Во втором примере пользователь может проверить, какой ключ он хочет проверить на наличие.
Example 1:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.obj1 = { "Prop_1": 1, "Prop_2": 2, "Prop_3": 3 }; $scope.res = ""; $scope.textval = "Prop_1"; $scope.checkK = function () { var txtVal = $scope.textval; if (!(txtVal in $scope.obj1)) { $scope.res = "Key not Exists."; } else { $scope.res = "Key Exists"; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Check if a key exists in an object in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Object - {{obj1}}<br><br> Enter the key: <input type="text" ng-model="textval"> <br><br> <button ng-click="checkK()"> Check here</button> <br><br> {{res}}<br> </div> </div></body> </html> |
Выход:

Example 2:
<!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.obj1 = { "Prop_1": 1, "Prop_2": 2, "Prop_3": 3 }; $scope.res = ""; $scope.textval = ""; $scope.checkK = function () { var txtVal = $scope.textval; if (!(txtVal in $scope.obj1)) { $scope.res = "Key not Exists."; } else { $scope.res = "Key Exists"; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Check if a key exists in an object in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Object - {{obj1}}<br><br> Enter the key: <input type="text" ng-model="textval"> <br><br> <button ng-click="checkK()"> Check here</button> <br><br> {{res}}<br> </div> </div></body> </html> |
Выход: