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]
CodePudding user response:
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.forEach((el, i) => {
newSelect.push({ select: selects[i], name: el.name });
});
console.log(newSelect);
CodePudding user response:
@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);
CodePudding user response:
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((select, index) => {
const newVal = {...select}
newVal.select = selects[index]
newSelects.push(newVal)
})
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((select, index) => {
const newVal = {...select}
newVal.select = selects[index]
return newVal
})
console.log(newSelects)
CodePudding user response:
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)