I'm trying to convert an array of strings to an array of objects after every 3rd index.
Input:
let tee = [
'Blue', '130',
'70.8', 'Blue',
'128', '708',
'White', '124',
'68.2'
]
Code:
function fillTeeBoxes(holesAmount) {
for (let i = 0; i < holesAmount.length; i ) {
let teeBox = ['tee', 'slope', 'rating']
let holeData = {};
for (let j = 0; j < 3; j ) {
holeData[teeBox[j]] = parseInt(getTeeBoxes[i]) || getTeeBoxes[i]
i
};
teeBoxes.push(holeData)
};
};
Expected Output:
tee = [
{tee: 'Blue', slope: 130, handicap: 70.8}
{tee: 'Blue', slope: 128, handicap: 70.8}
{tee: 'White', slope: 124, handicap: 68.2}
]
CodePudding user response:
We can use a for loop and iterate in steps of 3:
let tee = [
'Blue', '130',
'70.8', 'Blue',
'128', '708',
'White', '124',
'68.2'
];
var output = [];
for (var i=0; i < tee.length; i =3) {
var obj = {tee:tee[i], slope:tee[i 1], handicap:tee[i 2]};
output.push(obj);
}
console.log(output);