AngularJs Check if a key exists in an object
AngularJs Check if a key exists in an object : There are many ways to check whether a key value exists in an object or not. You can use pure JavaScript to check a key. Here in this tutorial we are going to explain how you can check that a key exists in an object or not. You can use our online editor to edit and run the code online.
AngularJs Check if a key exists in an object Example
You can simply use the (“key” in obj1) to check a key in an object it will return false if the key does not exist in object else it will return true. Here is an example to check key in javascript/angularjs object.
AngularJs Check if a key exists in an object Example:
<!DOCTYPE html> <html lang="en"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> <script> var myApp = angular.module("myApp", []); myApp.controller("myController", function($scope) { $scope.obj1 = {"key1":99}; $scope.result = ''; $scope.textvalue = "key1"; $scope.checkKey = function() { var txtVal = $scope.textvalue; if(!(txtVal in $scope.obj1)){ $scope.result = "Key not Found."; }else{ $scope.result = "Key Exists in Object obj1."; } } }); </script> </head> <body> <div ng-app="myApp"> <div ng-controller="myController"> <input type="text" ng-model="textvalue" ><br> <button ng-click ="checkKey()" >Check Key Exists</button> <br> Result = {{result}}<br> </div> </div> </body> </html> |
If you run the above example it will produce output something like this –
Advertisements