简体   繁体   English

为什么map mutate对象数组?

[英]Why does map mutate array of objects?

Might be a stupid question, but why does map mutate array of objects. 可能是一个愚蠢的问题,但为什么map mutate对象数组。

 var obj = { items: [{ value: 1, selected: true }, { value: 2, selected: false }] }; var items = obj.items.map(i => { if (i.value === 2) i.selected = true; return i; }); console.log(obj); 

When you map an array, it's not creating a copy of the object. 映射数组时,它不会创建对象的副本。 It's just iterating over the array. 它只是迭代数组。

If you don't want to mutate the object, you have to create a copy of the object: 如果您不想改变对象,则必须创建对象的副本:

var items = obj.items.map(item => {
    let i = JSON.parse(JSON.stringify(item))
    if (i.value === 2) i.selected = true;
    return i;
});

If you want a quick solution for an unmutable version of .map over an array of objects you can use the spread operator: 如果要在对象数组上快速解决.map不可变版本,可以使用扩展运算符:

myArrayOfObjects.map(({...obj}) => { });

Example: 例:

const foo = [];

for(let i = 0; i < 5; i++) {
    foo.push({label: "foo"});
}

const bar = foo.map(({...val}) => {
    val.id = Math.random();
  return val;
});

console.log(foo);
console.log(bar);

.map() as Hammerbot explained, does not create a copy, it creates a new array which directly references your object, thus mutating your object. Hammerbot解释说, .map()不会创建副本,它会创建一个直接引用您的对象的新数组,从而改变您的对象。

If you don't want to mutate your object, you can use Object.assign() within your mapping which creates a copy of the object. 如果您不想改变对象,可以在映射中使用Object.assign()来创建对象的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM