很抱歉,这个菜鸟问题,但是原始数组中的对象是如何被修改的?我提取了小片段。
mappedEvents.u
具有额外的属性,而原点update
没有mappedEvents.u
和update.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});
代码仍然在修改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});
我希望有帮助!