The first problem is that your
addKeyAndValue
function doesn't return anything. Remove the redundant braces to make it return the results of the
map
function.
const addKeyAndValue = (arr, key, value) => arr.map(obj => ...);
The second problem is that the arrow function you've passed to
map
also doesn't return anything. You will end up with an array containing the same number of elements, but each element will be
undefined
. Make the arrow function return something:
arr.map(obj => {
obj[key] = value;
return obj;
});
Demo[
^]
However, as you can see from the demo, although
map
returns a new array, it's only a shallow copy. Your new property is added to the elements in the source array as well, since they're pointing to the same objects.
If you don't want to modify the elements in the source array, you will need to copy them. The simplest option is probably to use the spread operator:
arr.map(obj => ({ ...obj, [key]: value}));
Demo[
^]
Spread syntax (...) - JavaScript | MDN[
^]