对象:深度省略 [英] Object: Deep omit

查看:109
本文介绍了对象:深度省略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在嵌套对象属性上使用 _。省略

Is there a way to use _.omit on nested object properties?

我希望这种情况发生:

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 显然不存在,只是 _。省略不会影响嵌套属性,但应该清楚我正在寻找什么。

_.nestedOmit obviously doesn't exist and just _.omit doesn't affect nested properties, but it should be clear what I'm looking for.

它也不一定是下划线,但根据我的经验,它通常会使事情更短更清晰。

It also doesn't have to be underscore, but in my experience it often just makes things shorter and clearer.

推荐答案

您可以创建一个 nestedOmit mixin,它将遍历该对象以删除不需要的密钥。类似

You could create a nestedOmit mixin that would traverse the object to remove the unwanted key. Something like

_.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/

这篇关于对象:深度省略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆