0

I try to make a copy of an array so I can do some manipulations without touching the original array but for some reason that doesn't work. When I manipulate the data of the newArray the originalArray also changes.

as far as I looked up this should work: const newArray = [...originalArray];

I also tried const newArray = [].from(originalArray); or const newArray = originalArray.slice(); but in all cases the original array is still modified.

I made a little example of what I'm trying to do

const originalArray = [{"main_options":{"ingredient_1":{"name":"minecraft:arrow","output_name":"drop_arrow"},"ingredient_2":{"name":"minecraft:lapis_lazuli","output_name":"drop_lapis_lazuli"},"stored_enchantments_id":"minecraft:projectile_protection","enchant_type":["helmet","chestplate","legging","boot"]},"books":[{"name":"Projectile Protection I","ingredient_1_count":8,"ingredient_2_count":4,"stored_enchantments_lvl":1},{"name":"Projectile Protection II","ingredient_1_count":16,"ingredient_2_count":8,"stored_enchantments_lvl":2},{"name":"Projectile Protection III","ingredient_1_count":24,"ingredient_2_count":12,"stored_enchantments_lvl":3},{"name":"Projectile Protection IV","ingredient_1_count":32,"ingredient_2_count":16,"stored_enchantments_lvl":4}]}, {"main_options":{"ingredient_1":{"name":"minecraft:iron_ingot","output_name":"drop_iron_ingot"},"ingredient_2":{"name":"minecraft:lapis_lazuli","output_name":"drop_lapis_lazuli"},"stored_enchantments_id":"minecraft:protection","enchant_type":["helmet","chestplate","legging","boot"]},"books":[{"name":"Protection I","ingredient_1_count":8,"ingredient_2_count":4,"stored_enchantments_lvl":1},{"name":"Protection II","ingredient_1_count":16,"ingredient_2_count":8,"stored_enchantments_lvl":2},{"name":"Protection III","ingredient_1_count":24,"ingredient_2_count":12,"stored_enchantments_lvl":3},{"name":"Protection IV","ingredient_1_count":32,"ingredient_2_count":16,"stored_enchantments_lvl":4}]}]
console.log("originalArray before manipulation");
console.log(JSON.stringify(originalArray));
const newArray = [...originalArray];

newArray.forEach((bookList, key) => {
    const books = bookList.books;
    const filteredBooks = books.filter(x => x.stored_enchantments_lvl === 3);
    newArray[key].books = filteredBooks;
});
console.log("====================================================");
console.log("originalArray after");
console.log(JSON.stringify(originalArray));
console.log("newArray after");
console.log(JSON.stringify(newArray));

https://jsfiddle.net/gr7q6ju2/1/

what am I doing wrong?

skara9
  • 3,458
  • 1
  • 3
  • 18
Christophe
  • 4,712
  • 5
  • 40
  • 82
  • 2
    if you original array is not shallow, consist of other objects, it will me modified as well, because methods like "spread', from, slice are doing shallow copy. What you need is deep copy. you can use `const newArray = JSON.parse(JSON.stringify(originalArray))` – AmirA Jan 26 '22 at 21:12

0 Answers0