I would like to filter an array of objects and update some value on the filtered entries. Here is my original code, without filtering:
let obj = {
foo: [
{
bar: "I should be modified",
modify: true,
},{
bar: "I should not be modified",
modify: false,
},{
bar: "I should be modified",
modify: true,
},
],
};
obj.foo.forEach((item, i) => {
let newItem = Object.assign({}, item);
newItem.bar = "I have been modified";
obj.foo[i] = newItem;
});
console.log(obj.foo);
/* Output:
[
{
bar: "I have been modified",
modify: true,
},{
bar: "I have been modified",
modify: false,
},{
bar: "I have been modified",
modify: true,
},
],
*/
Now I would like to replace .forEach(... with .filter(e => e.modify).forEach(.... So instead of modifying all the elements of obj.foo, only those with modify === true are modified. How can this be done without filtering again inside the forEach loop?
obj.foo.filter(e => e.modify).forEach((item, i) => {
let newItem = Object.assign({}, item);
newItem.bar = "I have been modified";
obj.foo[i] = newItem; // will not work as the index i is not correct from the original array
});
console.log(obj.foo);
/* Expected output:
[
{
bar: "I have been modified",
modify: true,
},{
bar: "I should not be modified",
modify: false,
},{
bar: "I have been modified",
modify: true,
},
],
*/
/* Actual output:
[
{
bar: "I have been modified",
modify: true,
},{
bar: "I have been modified",
modify: true,
},{
bar: "I should be modified",
modify: true,
},
],
*/
.filter(e => e.modify).forEach(...?filtermethod you will lose the correct index of the element. So without filtering you should be checking with anifstatement inside theforEachcallback.