Jimmy Obonyo Abor Jimmy Obonyo Abor - 2 months ago 19
Javascript Question

Underscore filter an object

I have an object like below I'd like to remove all key value where 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',
}
}
};


my current code

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)

Answer

I believe you're using the wrong variable for your inner function.

EDIT: Sorry, I got lazy and tried to write without testing. The above assertion is correct, but there are a few other errors as well, addressed in the updated code below

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 === '*');
  }
})
Comments