AngularJS检查对象是否具有特定值

时间:2017-02-06 11:44:18

标签: angularjs javascript-objects

我正在努力避免重复。如果我再次发送相同的名称(比如杰森),我不希望它第二次被添加到$ scope.people。如何在添加之前检查它?

$scope.people = [
  {
    name : "Jason",
    age : 26,
    height : 176,
  },
  {
    name : "Mark",
    age : 34
    height : 190
  }
];

$scope.add = function(name,age,height) {
  // How can I make sure that Jason or Mark won't get added again?
}

如果它是一个简单的数组,我会像下面一样解决它,但这是不同的。

$scope.add = function (name) {
  if ($scope.people.indexOf(name) == -1) {
    $scope.people.push(name);
  }
};

4 个答案:

答案 0 :(得分:2)

您可以使用isn't valid HTML,以下示例将向您展示。这是处理这种逻辑的常见AngularJS方法。好吧,这个解决方案将完全比较两个对象,而不是只比较一个对象的一个​​属性。

    $scope.add = function(name, age, height) {

        //init
        var found = false;

        //equal logic
        angular.forEach($scope.people, function (people) {
            if (angular.equals(people, {
                    name: name,
                    age: age,
                    height: height
                })) {
                found = true; //set found state
                return; // break angular.forEach()
            }
        });

        //proceed
        if (!found) {
            $scope.people.push({
                name: name,
                age: age,
                height: height
            });
        }
    };

答案 1 :(得分:1)

我从StackOverflow帖子中获取了这段代码,我现在无法找到。但这应该可以解决问题:

   function unique(collection, keyname) {
    var output = [],
        keys = [];

    angular.forEach(collection, function (item) {
        var key = item[keyname];
        if (keys.indexOf(key) === -1) {
            keys.push(key);
            output.push(item);
        }
    });
    return output;
};

用法:

$scope.people = unique(jsonArray, 'name');

答案 2 :(得分:1)

$。grep可能会帮助你

var result = $.grep(people, function(e){ return e.name == x.name; });

结果将是一系列匹配,所以你会知道是否有任何匹配。

答案 3 :(得分:0)

您可以使用$ filter轻松找到像这样的现有人

$scope.people = [{
    name: "Jason",
    age: 26,
    height: 176,
  }, {
    name: "Mark",
    age: 34,
    height: 190
  }];

  $scope.add = function(name, age, height) {
    if(doesntExist(name)){
      $scope.people.push({name: name, age: age, height: height})
    }
  }

  function doesntExist(name){
    return $filter('filter')($scope.people, {name: name}).length === 0
  }
工作人员 http://plnkr.co/edit/4z4ofqTMUH4rMzpoIsI5?p=preview