Removing object properties with Lodash

后端 未结 8 1402
旧巷少年郎
旧巷少年郎 2021-02-02 05:30

I have to remove unwanted object properties that do not match my model. How can I achieve it with Lodash?

My model is:

var model = {
   fname: null,
   lna         


        
相关标签:
8条回答
  • 2021-02-02 05:53

    You can use _.omit() for emitting the key from a JSON array if you have fewer objects:

    _.forEach(data, (d) => {
        _.omit(d, ['keyToEmit1', 'keyToEmit2'])
    });
    

    If you have more objects, you can use the reverse of it which is _.pick():

    _.forEach(data, (d) => {
        _.pick(d, ['keyToPick1', 'keyToPick2'])
    });
    
    0 讨论(0)
  • 2021-02-02 05:56

    This is my solution to deep remove empty properties with Lodash:

    const compactDeep = obj => {
        const emptyFields = [];
    
        function calculateEmpty(prefix, source) {
            _.each(source, (val, key) => {
               if (_.isObject(val) && !_.isEmpty(val)) {
                    calculateEmpty(`${prefix}${key}.`, val);
                } else if ((!_.isBoolean(val) && !_.isNumber(val) && !val) || (_.isObject(val) && _.isEmpty(val))) {
                    emptyFields.push(`${prefix}${key}`);
                }
            });
        }
    
        calculateEmpty('', obj);
    
        return _.omit(obj, emptyFields);
    };
    
    0 讨论(0)
提交回复
热议问题