Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object: Deep omit

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

I want this to happen:

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

like image 503
zimt28 Avatar asked May 12 '15 10:05

zimt28


2 Answers

Detailed solution of this issue is posted in another thread. Please have a look at the below thread

Link - Cleaning Unwanted Fields From GraphQL Responses

like image 55
Rigin Oommen Avatar answered Nov 10 '22 06:11

Rigin Oommen


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;
    }
});

and a demo http://jsfiddle.net/nikoshr/fez3eyw8/1/

like image 8
nikoshr Avatar answered Nov 10 '22 06:11

nikoshr