【问题标题】:Object: Deep omit对象:深度省略
【发布时间】:2015-07-23 03:34:54
【问题描述】:

有没有办法在嵌套对象属性上使用_.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 不会影响嵌套属性,但应该清楚我在寻找什么。

它也不必是下划线,但根据我的经验,它通常只会让事情变得更短更清晰。

【问题讨论】:

  • 嵌套是任意的还是只有一层?

标签: javascript underscore.js


【解决方案1】:

您可以创建一个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/

【讨论】:

    【解决方案2】:

    此问题的详细解决方案已发布在另一个线程中。请看下面的帖子

    链接 - Cleaning Unwanted Fields From GraphQL Responses

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多