Let's understand your code:
array.forEach(fruit => fruit.oranges === fruit.apple);
Let's expand the callback function:
array.forEach(fruit => {
return fruit.oranges === fruit.apple;
});
The forEach
method should be used only when you want to iterate over each element of the array. It won't do anything with the value you return from the given callback.
You could, however, modify the ===
operator (which shall be used to compare two values) to use the =
operator to reassign the value of the original fruit
's orange
property.
Like so:
const arr = [
{ apple: 2, oranges: 100 },
{ apple: 4, oranges: 120 },
{ apple: 6, oranges: 110 }
];
arr.forEach((fruit) => {
// Reassign the `oranges` property with the `apple` value:
fruit.oranges = fruit.apple
});
console.log(arr);
Notice that forEach
does not return the array. In this case, we are just iterating over each element and modifying each element's oranges
property.
Another option, when you do NOT want to modify the original values is to use Array.prototype.map
instead of Array.prototype.forEach
.
Check out this question to find out the differences between map
and forEach
.
Something like:
const arr = [
{ apple: 2, oranges: 100 },
{ apple: 4, oranges: 120 },
{ apple: 6, oranges: 110 }
];
const newArr = arr.map((obj) => ({
// Forward the apple property:
apple: obj.apple,
// Assign a new value to the oranges property:
oranges: obj.apple
}));
console.log(newArr);
I must add that with that code, you will not, in fact, modify the array nor its original objects. You are instead creating a new array (returned by map
) with new objects.