Reputation: 99
I'm trying to duplicate some items of an array. I change some objects with new id's, the problem is that not only the new array is modified but also the original.
The code I use:
function cloneProductLine(oldGroupIndex) {
// Create new instance of the product lines
let items = [...productLines];
let group = items.find((line, index) => index === parseFloat(oldGroupIndex));
// Get product lines with same parent group Id
items = items.filter((line) => line.parent_group_id === group.group_id);
items.forEach((line) => line.parent_group_id = getNewGroupId());
// Set new Id for group
group.group_id = getNewGroupId();
productLines = [...productLines, group, ...items];
renderProductLine();
}
What am I doing wrong?
Upvotes: 1
Views: 48
Reputation: 5982
Or Simple way
let items = JSON.parse(JSON.stringify(productLines));
Upvotes: 1
Reputation: 45121
let items = [...productLines];
creates a shallow array copy. Means all items are the same though the array is new.
You need to create a deeper copy (create new items as well)
Assuming items are plain old objects you could do
let items = productLines.map(item => ({...item});
Upvotes: 1