Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array.map copy without changing original

Tags:

javascript

I've noticed that deleting object properties when using Array.map() affects the original array, I assume since each iteration's item is still referencing the original array:

var objects = [{name: 'a', password: 'x'}, {name: 'b', password: 'x'}];

var clean = objects.map(user => {delete user.password; return user;});

console.log(JSON.stringify(objects));
> [{"name":"a"},{"name":"b"}]

Is there a way to use map or filter without it modifying the original? I can think to loop through each item and create a clone but curious if there's a simpler way.

like image 367
d-_-b Avatar asked Mar 02 '26 08:03

d-_-b


1 Answers

You can reference everything except password with dereferencing. Then use map to build a new object with everything else. This is nice if you have other properties on the object other than name and want to include everything except password.

var objects = [{name: 'a', password: 'x'}, {name: 'b', password: 'x'}];

var clean = objects.map(({password, ...user}) => user);

console.log(objects);  // untouched

console.log(clean);    // no password
like image 99
Mark Avatar answered Mar 03 '26 21:03

Mark