javascript - push if not exist in array object -
i have below model in js . using angular js
$scope.data = { focuson: " ", filters: [], range: { from: "", to: "" } }
i have below function :
$scope. addfield = function ($type, $value) { $scope.data1 = { filtername: $type, filtervalue: $value }; if ($scope.data.filters[$type] === undefined) { $scope.data.filters.push($scope.data1); } $scope.data1 = ""; $scope.json = angular.tojson($scope.data); };
i want push filters if not available already. how can this.
i have tried above dint work. went wrong. can please me,
thanks,
so assuming $scope.data.filters
array of objects filtername
, filtervalue
property.
in case, need search array see if matching object exists before inserting it, comparing values of properties of object (a deep equality check, opposed shallow equality check, indexof()
does).
if use lodash or underscore, can use _.findwhere()
helper easily:
if (!_.findwhere($scope.data.filters, $scope.data1)) { $scope.data.filters.push($scope.data1); }
otherwise, make own function, full code looks like:
$scope.addfield = function ($type, $value) { $scope.data1 = { filtername: $type, filtervalue: $value }; if (!filterexists($type)) { $scope.data.filters.push($scope.data1); } $scope.data1 = ""; $scope.json = angular.tojson($scope.data); }; function filterexists(type) { (var = 0, len = $scope.data.filters.length; < len; i++) { if ($scope.data.filters[i].filtername === type) return true; } return false; }
Comments
Post a Comment