簡體   English   中英

檢查對象中是否存在元素

[英]Check if an element exists in a object

我有一組單選按鈕,當選擇一個單選按鈕時,該元素將推入對象。

然后,我需要獲取對象中元素的值,然后將它們推入數組(如果它們尚未包含在數組中)。

我的問題是,使用此函數在每個值的數組中不斷出現重復項或重復項,因為我沒有正確檢查它們是否存在。

如何檢查元素是否已存在於我的數組中,然后將其排除在外?

      _this.selected = {};
      _this.selectedArray = [];

      //loop through the object
      angular.forEach(_this.selected, function ( item ){

        //if it is not the first time the array is getting data loop through the array
        if(_this.selectedArray.length > 0) {
          _this.selectedArray.forEach(function (node){

            //check to see if the item already exists-- this is where it is failing
            //and running the loop too many times 
            if(node.id !== item.id){
              _this.selectedArray.push(item);
            }
          });
        } else {
          _this.selectedArray.push(share);
        }
      });

您可以使用其他哈希值檢查是否已將項目添加到數組。

  _this.selected = {};
  _this.selectedArray = [];
  _this.selectedHash = {};

  //loop through the object
  angular.forEach(_this.selected, function ( item ){
      if(_this.selectedHash[item.id]) { return; }

      _this.selectedArray.push(item);
      _this.selectedHash[item.id] = 1;         
  });

您是否嘗試過jQuery的inArray http://api.jquery.com/jquery.inarray

它的工作原理與StringindexOf方法相同。

您可以嘗試if $.inArray(node, selectedArray) == -1 // element is not in the array

您可以在該數組上運行此函數以將其減少為唯一值,而不是應用復雜的代碼來檢查該數組是否有元素

var getOnlyUniqueValuesInArray = function(arrayObj) {
    return arrayObj.reduce(function(a, b) {
        if (a.indexOf(b) < 0) a.push(b);
        return p;
    }, []);
};

嗨,那應該有幫助

var app = angular.module('app', []);

app.controller('firstCtrl', function($scope){


var app = angular.module('app', []);

app.controller('firstCtrl', function($scope) {
  _this.selected = {};
  _this.selectedArray = [];

  //loop through the object
  angular.forEach(_this.selected, function(item) {

    //if it is not the first time the array is getting data loop through the array
    if (_this.selectedArray.length > 0) {

      var canAdd = true;
      _this.selectedArray.forEach(function(node) {

        //do not add iny any of node.id will be equal to item.id
        if (node.id == item.id) {
          canAdd = false;
        }

      });
      if(canAdd){
        _this.selectedArray.push(item);
      };
    } else {
      _this.selectedArray.push(share);
    }
  });

})

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM