Assumption (based on tutorials and reading material): Example; https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns
Updating an object property in an array best practice is through map versus foreach. Every example as per the redux breaks out map into two functions 1. Update object properties/s and return object. Even on medium and other expert content it follows this format
Example:
I'm iterating through an array of objects and updating every boolean active flag based on on whether that object's id property === id argument.
let items = [{id:1,active:false},{id:2,active:false},{id:3,active:false}];
const traditional = (items,id) => items.map(item => {
item.active = item.id === id;
return item
})
console.log("traditional ", traditional(items, 3));
// outcome: [{id:1,active:false},{id:2,active:false},{id:3,active:true}];
Question:
I've been using a combination of Object assign and map to condense the code, but I'm told that is bad practice and should stop. What am I missing i.e. what's the problem with this approach?
let items = [{id:1,active:false},{id:2,active:false},{id:3,active:false}];
const updateItemsById = (items,id) => items.map(item => Object.assign(item, {active: (item.active = item.id === id)}))
console.log("update ", updateItemsById(items, 2));
.map()is still mutating each object. If your goal is to have a pure operation, then you can useObject.assign({}, item, {active: (item.active = item.id === id)})- copy the object and overwriteactive.