为什么过滤然后映射会更改javascript中的原始数组[重复]

const words = [{ref : "a", list: "a & b & c & d"},
              {ref : "a", list: "a & b & c & d"},
              {ref : "b", list: "aa & bb & cc & dd"},
              {ref : "c", list: "aaa & bbb & ccc & ddd"}];

 var data = words.filter(item => {
            if (item.ref == "a")
              return item;
        });

let result = data.map(o => {
            o.list = o.list.split('&').map(key => ({
                selected: false,
            }))
            return o;
        });
console.log(words);
console.log(result);
  • I have words array
  • after filtering for ref : a i'm getting new array data
  • but when i modifiy the data's object it is reflecting on main array words's. which should not happen.
words
> Array [
Object { ref: "a", list: Array [Object { selected: false }, Object { selected: false }] },
Object { ref: "a", list: Array [Object { selected: false }, Object { selected: false }] },
Object { ref: "b", list: "aa & bb" },
Object { ref: "c", list: "aaa & bbb" }
]

result
> Array [
Object { ref: "a", list: Array [Object { selected: false }, Object { selected: false }] },
Object { ref: "a", list: Array [Object { selected: false }, Object { selected: false }] }
]
  • In words you can see ref b and ref c is not modified
  • but ref a is changed. which should not happen in my case

* How to avoid alteration of original array words ? *

评论
  • 学会爱
    学会爱 回复

    Your .map() call changes the list property of the original object. map() returns a new array, but if you change the objects inside it directly, they are affected. Objects are always passed by a reference.

    To prevent your map() changing the original array, you need to return a copy of each element:

    let result = data.map(o => ({
        ...o,
        list: o.list.split('&').map(key => ({
            selected: false,
        }))
    }));
    

    Of note, you also use filter() wrong. In filter(), you should return true or false to, respectively, keep or reject an element. It's enough to return the result of your condition:

    var data = words.filter(item => {
        return item.ref == "a";
    });