Lodash cloneDeepWith to omit undefined

后端 未结 3 1223
你的背包
你的背包 2021-01-05 10:19

I wrote a customozer function to omit the undefined values of the object with cloneDeepWith. However on the immutable return, it is not digging in recursively.

3条回答
  •  醉酒成梦
    2021-01-05 10:55

    As far as I know _.cloneDeepWith() customizer is a bit misleading. The customizer should handle only non object values. If it handles object values, it should also continue the recursion by itself. For example, you can see that as the customizer is called, the cloning is handled by value.cloneNode(true). As you can see only body appears in the console.

    const { cloneDeepWith, isObject } = _;
    
    function customizer(value) {
      console.log(value);
      if (_.isElement(value)) {
        return value.cloneNode(true);
      }
    }
     
    var el = _.cloneDeepWith(document.body, customizer);

    However, if you just customize non object values, and return undefined for object values, which prompts the method to handle them (documented in cloneDeep), it iterates everything:

    const { cloneDeepWith, isObject, isUndefined } = _;
    
    const obj = {
      a0: true,
      b0: true,
      c0: undefined,
      obj1: {
        a1: true,
        b1: true,
        c1: undefined
      }
    };
    
    const result = cloneDeepWith(obj, v => {
      console.log(v);
      
      return isObject(v) ? undefined : 'custom value';
    });
    
    console.log(result);

    To solve your problem, you can use _.transform() recursively to take all values that are not undefined:

    const { transform, isObject, isUndefined } = _;
    
    const obj = {
      a0: true,
      b0: true,
      c0: undefined,
      obj1: {
        a1: true,
        b1: true,
        c1: undefined
      }
    };
    
    const cloneDeepWithoutUndefined = (obj) =>
      transform(obj, (r, v, k) => {
        if(isUndefined(v)) return;
        r[k] = isObject(v) ? cloneDeepWithoutUndefined(v) : v;
      });
      
    const result = cloneDeepWithoutUndefined(obj);
    
    console.log(result);

提交回复
热议问题