Object.assign—override nested property

2020-02-16 12:12发布

I have an Object a like that:

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

whereby there are a lot more properties in a.user

And I would like to change only the a.user.groups value. If I do this:

const b = Object.assign({}, a, {
  user: {
    groups: {}
  }
});

b doesn't have any other Property except b.user.groups, all others are deleted. Is there any ES6 way to only change the nested property, without loosing all the other, with Object.assign?

8条回答
我命由我不由天
2楼-- · 2020-02-16 12:17

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

查看更多
对你真心纯属浪费
3楼-- · 2020-02-16 12:26

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

assign method will make a new object by copying from the source object, the issue if you change any method later on in the source object it will not be reflected to the new object.

Use create()

The Object.create() method creates a new object with the specified prototype object and properties.

const b = Object.create(a)
b.user.groups = {}
// if you don't want the prototype link add this
// b.prototype = Object.prototype 

This way you have b linked to a via the prototype and if you make any changes in a it will be reflected in b, and any changes in b will not affect a

查看更多
来,给爷笑一个
4楼-- · 2020-02-16 12:26

More general solution below. It makes recursively assigning only if there are conflicts (same key names). It resolves issues assigning complex objects, which has many reference points. For example, nested-object-assign, an existing package for nested object assign in npm, stuck with complex objects assign because it recursively goes through all keys.

var objecttarget = {
  a: 'somestring',
  b: {x:2,y:{k:1,l:1},z:{j:3,l:4}},
  c: false
};

var objectsource = {
  a: 'somestring else',
  b: {k:1,x:2,y:{k:2,p:1},z:{}},
  c: true
};

function nestedassign(target, source) {
  Object.keys(source).forEach(sourcekey=>{
    if (Object.keys(source).find(targetkey=>targetkey===sourcekey) !== undefined && typeof source[sourcekey] === "object") {
      target[sourcekey]=nestedassign(target[sourcekey],source[sourcekey]);
    } else {
      target[sourcekey]=source[sourcekey];
    }
  });
  return target;
}

// It will lose objecttarget.b.y.l and objecttarget.b.z
console.log(Object.assign(Object.create(objecttarget),objectsource));

// Improved object assign
console.log(nestedassign(Object.create(objecttarget),objectsource));

查看更多
男人必须洒脱
5楼-- · 2020-02-16 12:28

You can change it this way,

const b = Object.assign({}, a, {
  user: Object.assign({}, a.user, {
          groups: {}
        })
});

or just do,

const b = Object.assign({}, a);
b.user.groups = {};
查看更多
劳资没心,怎么记你
6楼-- · 2020-02-16 12:32

Small fine tune of phillips first answer.

const object1 = {
  abc: {
    a: 1
  }
};

const object2 = {
  abc: {
    b: 2
  }
};

Object.assign(object1, {
    abc: {
        ...object1.abc,
        ...object2.abc
    }
});

console.log(object1);
// Object { abc: Object { a: 1, b: 2 } }
查看更多
Root(大扎)
7楼-- · 2020-02-16 12:37

when having nested object i prefer using this little hack .

const a = JSON.parse(JSON.stringify(b))
查看更多
登录 后发表回答