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'
}];
Share
Improve this question
edited Mar 8, 2019 at 17:26
jo_va
14k3 gold badges25 silver badges49 bronze badges
asked Mar 8, 2019 at 13:56
bharath bhushanbharath bhushan
2171 gold badge4 silver badges11 bronze badges
3
- What have you tried so far? – Anurag Srivastava Commented Mar 8, 2019 at 13:58
- 2 In a functional paradigm, you wouldn't be changing the array but making a copy. With that said, it also depends on what exactly you'd even want to do - if you want to only operate on the first element, you're most likely going to take that element and work with it, as opposed to operating on the array in order to do something only with the first element. – VLAZ Commented Mar 8, 2019 at 13:58
- 2 Change it how? – Pointy Commented Mar 8, 2019 at 13:58
3 Answers
Reset to default 3Here 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);
You can use map
and create a new array
let value = 'abc';
let arr = [{
'first': 'aaa'
}, {
'first': 'bbb'
}, {
'first': 'ccc'
}];
let newArr = arr.map(function(item) {
return {
first: value
}
})
console.log(newArr)
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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744785328a4593586.html
评论列表(0条)