2016-11-24 30 views
1

基于下面的快速样机,我需要将URL路由对象添加到我的应用中的Array属性。检测JavaScript中的重复对象属性

在下面 addAppRoute(routeObbj)功能

我想添加一个检查,看看是否被添加了新的途径已经存在或者没有在物业this.cache.webDevAppRoutes

我怎样才能确保重复不加?这将需要基于重复moduleaction是相同的

var app = { 
    cache: { 
     webDevAppRoutes: [], 
    }, 

    addAppRoute: function(route) { 
     var routes = this.cache.webDevAppRoutes; 
     routes.push(route); 
    }, 

    getAppRoutes: function() { 
     var routes = this.cache.webDevAppRoutes; 
     console.log(routes); 
    }, 

    addBookmarkAppRoutes: function() { 

     this.addAppRoute({ 
      module: 'bookmarks', 
      action: 'view', 
      params: [{ 
       id: 123 
      }], 
     }); 

     this.addAppRoute({ 
      module: 'bookmarks', 
      action: 'edit', 
      params: [{ 
       id: 123 
      }], 
     }); 

     this.addAppRoute({ 
      module: 'bookmarks', 
      action: 'add', 
      params: [], 
     }); 
    }, 

} 

回答

2

通过数组只是循环,并检查它不已经有一个moduleaction的条目。您可以使用Array#some,例如:

if (routes.some(function(r) { return r.module == route.module && r.action == route.action)) { 
    // It's a duplicate 
} 

Array#some回报true只要其回调调用返回truthy值;否则,返回false

在ES2015,这是多一点简洁:

if (routes.some(r => r.module == route.module && r.action == route.action)) { 
    // It's a duplicate 
}