How to change the arr['first'] of each object in a functional programming style using forEach, map, reduce, filter etc.
let value = 'abc'
let arr = [{
'first': 'aaa'
},{
'first': 'bbb'
},{
'first': 'ccc'
}];
How to change the arr['first'] of each object in a functional programming style using forEach, map, reduce, filter etc.
let value = 'abc'
let arr = [{
'first': 'aaa'
},{
'first': 'bbb'
},{
'first': 'ccc'
}];
Here is an immutable way to update the property first of each item in your array. It uses Array.map() to create a new array and the spread operator to copy each item and set the first property to value:
const value = 'abc';
const arr = [{ 'first': 'aaa' },{ 'first': 'bbb' },{ 'first': 'ccc' }];
const newArr = arr.map(item => ({ ...item, first: value }));
console.log(newArr);
If you want to mutate the original array, which is not a good idea with the functional paradigm, use Array.forEach() instead:
const value = 'abc';
const arr = [{ 'first': 'aaa' },{ 'first': 'bbb' },{ 'first': 'ccc' }];
arr.forEach(item => item.first = value);
console.log(arr);
if I good understand you, you want to change key name 'first' in every object of array using map?
you can try below code:
const value = 'abc';
const arr = [{
'first': 'aaa'
},{
'first': 'bbb'
},{
'first': 'ccc'
}];
const newArr = arr.map(obj => {
if ('first' !== value) {
Object.defineProperty(obj, value,
Object.getOwnPropertyDescriptor(obj, 'first'));
delete obj['first'];
}
return obj;
});
console.log(newArr);
or if you want to change only value of first in every obj:
const value = 'abc';
const arr = [{
'first': 'aaa'
},{
'first': 'bbb'
},{
'first': 'ccc'
}];
const newArr = arr.map(obj => ({...obj, first: value}));
console.log(newArr);