I am trying to transform the objects in an array adding a new property number. The value of this property must be obtained from the array set using sequential values, so that the first object should have the value 1 the second the value 3 and the third the value 6 the fourth the value 1 again and so on ...
This is what I've been trying
const set = [1, 3, 6];
const data = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }];
let position = 0;
const getItem = () => {
if (position === 0) {
position += 1;
return set[0];
}
if (position <= set.length - 1) {
return set[position];
}
return set[0];
};
const output = data.map((entry, index) => ({ ...entry, number: getItem() }));
console.log(output);
And this is the expected output
[
{ id: 1, number: 1 },
{ id: 2, number: 3 },
{ id: 3, number: 6 },
{ id: 4, number: 1 },
{ id: 5, number: 3 },
{ id: 6, number: 6 },
];