借助散布运算符修改对象的属性会导致原始对象被修改?

时间:2020-02-04 19:29:22

标签: javascript arrays maps

很抱歉出现noob问题,但是如何修改原始数组中的对象?我提取了小片段。

  • 预期:mappedEvents.u有额外的属性,而原产地update没有
  • 发生了:mappedEvents.uupdate.u具有相同的值。

 const update= [
        {
            "_id": "2QK5mmqERN8dd6LaL",
            "open": true,
            "alert": false,
            "unread": 0,
            "userMentions": 0,
            "groupMentions": 0,
            "ts": "2019-09-20T03:20:50.927Z",
            "rid": "GENERAL",
            "name": "general",
            "t": "c",
            "u": {
                "_id": "5JzjbnZDcxKMYR2mv",
                "username": "honga",
                
            },
            "_updatedAt": "2020-01-02T06:34:53.747Z",
            "ls": "2020-01-02T06:34:53.681Z"
        },
        {
            "_id": "ox3hxbxdKpenLmyKT",
            "rid": "5JzjbnZDcxKMYR2mvyBShq8ZDfx9isv2sA",
            "u": {
                "_id": "5JzjbnZDcxKMYR2mv",
                "username": "honga",
                
            },
            "_updatedAt": "2020-01-16T10:32:43.414Z",
            "alert": false,
            "fname": "lolo",
            "groupMentions": 0,
            "ls": "2020-01-16T10:32:43.414Z",
            "name": "lol",
            "open": true,
            "t": "d",
            "ts": "2020-01-16T09:26:13.665Z",
            "unread": 0,
            "userMentions": 0
        }
    ];

const mappedEvents = update.map(e => {
  e.u = {...e.u,"avatarOrigin": "upload"};
  return e;
});
console.log({update});
console.log({mappedEvents});

1 个答案:

答案 0 :(得分:1)

代码仍在访问原始元素的引用,您可以在其中修改e.u属性。这已经反映在原始数组上。如果只想使用.map()创建新元素,则需要克隆当前元素以及从.map()作为参数获得的内容。

尝试以下操作:

const update = [{"_id": "2QK5mmqERN8dd6LaL","u": {"_id": "5JzjbnZDcxKMYR2mv","username": "honga"}},{"_id": "ox3hxbxdKpenLmyKT","u": {"_id": "5JzjbnZDcxKMYR2mv","username": "honga",}}];

const mappedEvents = update.map(e => {
  const newElem = {...e};
  newElem.u = {...e.u,"avatarOrigin": "upload"};
  return newElem;
});
console.log({update});
console.log({mappedEvents});

希望对您有帮助!