Lodash cloneDeepWith to omit undefined

后端 未结 3 1228
你的背包
你的背包 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 11:17

    This can be solved by using recursively lodash transform method via:

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

    You could also do this in ES6 only via Object.entries & reduce:

    const obj = { a0: true, b0: true, c0: undefined, obj1: { a1: true, b1: true, c1: undefined } };
    
    const cloneMe = (obj) => {
       return Object.entries(obj).filter(([k,v]) => 
          v != undefined).reduce((r,[k,v]) => {
            r[k] = (v instanceof Object) ? cloneMe(v) : v
            return r
       },{})
    }
    
    console.log(cloneMe(obj))

    You can additionally extend the check for object if instance of Object is not sufficient etc.

提交回复
热议问题