与角形物体比较

时间:2016-09-14 11:41:07

标签: javascript angularjs

跟随我的角对象

  $scope.obj1= [
    {"NewID":38,"Type":"Faculty","Year":"2016","Status":"Active"},
    {"NewID":39,"Type":"Staff","Year":"2016","Status":"Active"},
    {"NewID":40,"Type":"Faculty","Year":"2016","Status":"Active"},
    {"NewID":41,"Type":"Faculty","Year":"2016","Status":"Active"}
 ]

我想检查一下' Type'包含任何'员工'或者'教师'为此,我使用以下代码

      var myobj=$scope.obj1;

       var x=false; y=false;

          for (var i = 0; i < myobj.length; i++) {
            if ( myobj[i].Type == 'Faculty') {                    
                x=true;
                break;
            }

          }
         for (var i = 0; i < myobj.length; i++) {

            if ( myobj[i].Type == 'Staff') {
                y=true;  
               break;               
            }
          }

我使用JavaScript,我正在寻找角度或JavaScript的简单方法,而不是使用for循环

3 个答案:

答案 0 :(得分:5)

var filteredObjects = $scope.obj1.filter(function(obj){
   return obj.Type === 'Faculty' || obj.Type === 'Staff';
})

这会返回一个包含已过滤对象的数组(类型&#39; Faculty&#39;&#39; Staff&#39;)。您可以查看length以查看是否有您需要的任何其他操作。

修改
因为您只想检查它是否包含任何&#39; Faculty&#39;或者&#39;员工&#39;你应该使用Array.prototype.some代替。

var exists = $scope.obj1.some(function (obj) { 
    return obj.Type === 'Faculty' || obj.Type === 'Staff';
}

对于单独的结果,您只需创建function

即可
function checkExists (type) {
    return $scope.obj1.some(function (obj) { 
        return obj.Type === type;
    }
}
var facultyExist = checkExists('Faculty');
var staffExist = checkExists('Staff');

答案 1 :(得分:3)

filter每次都会创建一个新数组,如果您需要知道对象是否存在,请尝试这个:

obj1= [
    {"NewID":38,"Type":"Faculty","Year":"2016","Status":"Active"},
    {"NewID":39,"Type":"Staff","Year":"2016","Status":"Active"},
    {"NewID":40,"Type":"Faculty","Year":"2016","Status":"Active"},
    {"NewID":41,"Type":"Faculty","Year":"2016","Status":"Active"}
 ];

 const includes = -1 !== obj1.findIndex(item => item.Type === "Faculty" || item.Type === "Staff" );

// in case your browser doesnt support arrow functions:
 const includes2 = 
    -1 !== obj1.findIndex(
    function (item) {
      return  item.Type === "Faculty" || item.Type === "Staff";
      }
    );

答案 2 :(得分:0)

  obj1.forEach(function(val,index){
  if(val.type=='Faculty)
  {
   //your code
   } 
  else if(val.type == 'Staff')
  {
     //your code
 })