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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With