Object.assign—override nested property

前端 未结 7 475
轮回少年
轮回少年 2020-12-13 01:36

I have an Object a like that:

const a = {
  user: {
   …
   groups: […]
   …
  }
}

whereby there are a lot more properties in

7条回答
  •  孤街浪徒
    2020-12-13 02:15

    Here's a small function called Object_assign (just replace the . with a _ if you need nested assigning)

    The function sets all target values by either pasting the source value in there directly, or by recursively calling Object_assign again when both the target value and source value are non-null objects.

    const target = {
      a: { x: 0 },
      b: { y: { m: 0, n: 1      } },
      c: { z: { i: 0, j: 1      } },
      d: null
    }
    
    const source1 = {
      a: {},
      b: { y: {       n: 0      } },
      e: null
    }
    
    const source2 = {
      c: { z: {            k: 2 } },
      d: {}
    }
    
    function Object_assign (target, ...sources) {
      sources.forEach(source => {
        Object.keys(source).forEach(key => {
          const s_val = source[key]
          const t_val = target[key]
          target[key] = t_val && s_val && typeof t_val === 'object' && typeof s_val === 'object'
                      ? Object_assign(t_val, s_val)
                      : s_val
        })
      })
      return target
    }
    
    console.log(Object_assign(Object.create(target), source1, source2))

提交回复
热议问题