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 arraydata
- but when i modifiy the
data
's object it is reflecting on main arraywords
'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
andref 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 thelist
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:Of note, you also use
filter()
wrong. Infilter()
, you should returntrue
orfalse
to, respectively, keep or reject an element. It's enough to return the result of your condition: