下划线过滤对象

时间:2016-09-29 21:43:58

标签: javascript underscore.js

我有一个像下面这样的对象我想删除key =' /'

中的所有键值
let routes = {
   '/dashboard': {
        name : 'Dashboard',
        component : appDashboard,
        icon: 'fa fa-dashboard',
        subRoutes: {
           '/': {

              component:appDashEcommerce
          },
          '/ecommerce': {
              name : 'Ecommerce',
              component:appDashEcommerce
          },

        }

    },
    '/apps': {
        name : 'Apps',
        component : appAppsPage,
        icon : 'fa fa-th',
        subRoutes: {
            '/': {

              component:appInbox
            },
            '/mailbox': {
              name : 'maibox',
              component : appInbox,
              icon : 'fa fa-th',
            }
      }
};

我当前的代码

var ret2 =  _.omit(routes, function(val, key, object) {
         if(_.has(val , 'subRoutes')){
            _.omit(val.subRoutes , function(v, k, o) { 
                return key === '/'
            })
          }else{

            return key === '/' || key === '*'
         }
       })

     console.log(ret2)

1 个答案:

答案 0 :(得分:1)

我相信你的内部功能正在使用错误的变量。

编辑:对不起,我很懒,试着写不经测试。上面的断言是正确的,但也有一些其他错误,在下面的更新代码中解决

https://jsfiddle.net/e708gyna/

//_.omitBy should be used for functions according to the lodash spec
var ret2 =  _.omitBy(routes, function(val, key, object) {
  if(_.has(val , 'subRoutes')) {
    //In order to use the result below, we need to store it
    val.subRoutes = _.omitBy(val.subRoutes , function(v, k, o) {
      //Since you're running this on the subRoutes
      //you need to test the key that you've defined
      //for this inner handler
      return (k === '/');
    })
  } else {
    return (key === '/' || key === '*');
  }
})