'How can update values in an array of objects?
how to get new array newSelect using map ,forEach
const selects = [false, true, true, true, false];
const oldSelects = [
{ select: true, name: 'AA' },
{ select: true, name: 'AA' },
{ select: true, name: 'AA' },
{ select: true, name: 'AA' },
{ select: true, name: 'AA' },
];
const newSelect = [
{ select: false, name: 'AA' },
{ select: true, name: 'AA' },
{ select: true, name: 'AA' },
{ select: true, name: 'AA' },
{ select: false, name: 'AA' },
];
oldSelects[0].select === selects[0]
Solution 1:[1]
@Inder answer is great, but a map looks more clean imo:
const selects = [false, true, true, true, false];
const oldSelects = [{
select: true,
name: "AA"
},
{
select: true,
name: "AA"
},
{
select: true,
name: "AA"
},
{
select: true,
name: "AA"
},
{
select: true,
name: "AA"
}
];
const newSelect = oldSelects.map((el, i) => ({
select: selects[i],
name: el.name
}));
console.log(newSelect);
Solution 2:[2]
Hey you can map the old array to a new one.
const selects = [false, true, true, true, false];
const oldSelects = [{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
];
const newSelect = oldSelects.map((object, index) => {
object['select'] = selects[index]
return object;
})
console.log(newSelect)
Solution 3:[3]
Using forEach
const selects = [false, true, true, true, false];
const oldSelects = [{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
];
const newSelects = []
oldSelects.forEach((selectItem, index) => newSelects.push({...selectItem, select: selects[index]}))
console.log(newSelects)
Using map
const selects = [false, true, true, true, false];
const oldSelects = [{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
{
select: true,
name: 'AA'
},
];
const newSelects = oldSelects.map((selectItem, index) => ({...selectItem, select: selects[index]}))
console.log(newSelects)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | RenaudC5 |
Solution 2 | RenaudC5 |
Solution 3 |