2015-05-12 71 views
5

有没有办法在嵌套的对象属性上使用_.omit对象:深忽略

我希望这种情况发生:

schema = { 
    firstName: { 
    type: String 
    }, 
    secret: { 
    type: String, 
    optional: true, 
    private: true 
    } 
}; 

schema = _.nestedOmit(schema, 'private'); 

console.log(schema); 
// Should Log 
// { 
// firstName: { 
//  type: String 
// }, 
// secret: { 
//  type: String, 
//  optional: true 
// } 
// } 

_.nestedOmit显然并不存在,只是_.omit不影响嵌套的属性,但它应该是清楚我在寻找。

它也不一定是下划线,但根据我的经验,它往往只是使事情变得更短,更清晰。

+0

事情会嵌套任意或只是一个水平? – thefourtheye

+0

将是任意的。 – zimt28

回答

7

您可以创建一个nestedOmit mixin来遍历对象以删除不需要的密钥。像

_.mixin({ 
    nestedOmit: function(obj, iteratee, context) { 
     // basic _.omit on the current object 
     var r = _.omit(obj, iteratee, context); 

     //transform the children objects 
     _.each(r, function(val, key) { 
      if (typeof(val) === "object") 
       r[key] = _.nestedOmit(val, iteratee, context); 
     }); 

     return r; 
    } 
}); 

和演示http://jsfiddle.net/nikoshr/fez3eyw8/1/