I have an array of objects that I need to deep copy and make modifications to each object without altering the original array or its contents. Here is my approach in JavaScript, but I am open to suggestions on a better method.
const users =
[
{
id : 1,
name : 'Jack',
approved : false
},
{
id : 2,
name : 'Bill',
approved : true
},
{
id : 3,
name : 'Rick',
approved : false
},
{
id : 4,
name : 'Rick',
approved : true
}
];
const users2 =
users
.map(
(u) =>
{
return Object.assign({}, u);
}
)
.map(
(u) =>
{
u.approved = true;
return u;
}
);
console.log('New users2 array of objects:')
console.log(users2);
console.log('The original users array remains untouched:')
console.log(users);
Output:
New users2 array of objects:
[ { id: 1, name: 'Jack', approved: true },
{ id: 2, name: 'Bill', approved: true },
{ id: 3, name: 'Rick', approved: true },
{ id: 4, name: 'Rick', approved: true } ]
The original users array remains untouched:
[ { id: 1, name: 'Jack', approved: false },
{ id: 2, name: 'Bill', approved: true },
{ id: 3, name: 'Rick', approved: false },
{ id: 4, name: 'Rick', approved: true } ]