I have an array
const head = [
{
"id": 1,
"name": "AK47",
"norms": "15-18",
"times": 2
},
{
"id": 2,
"name": "Deagle",
"norms": "13-21",
"times": 1
}
]
arrays should be created from it according to the number of times properties
Something like that:
const tail = [
{
"id": 1,
"headId": 1,
"time": 1,
"check": 16,
"status": "ok"
},
{
"id": 2,
"headId": 1,
"time": 2,
"check": 14,
"status": "less"
},
{
"id": 3,
"headId": 2,
"time": 1,
"check": 23,
"status": "excess"
}
]
"times": 2
was therefore 2 arrays created. Inside them is the property time meaning which time of times
How can I implement this solution more conveniently and correctly. I will be glad for any help
CodePudding user response:
Your explanation is still a bit unclear, but from what I've understood, the code below might be the answer you're looking for. It loops through the head
elements and then loops x
number of times, where x
equals the times
property. It creates an array for each element in head
and then flattens it to generate the desired 1D array output.
const head = [{
"id": 1,
"name": "AK47",
"norms": "15-18",
"times": 2
},
{
"id": 2,
"name": "Deagle",
"norms": "13-21",
"times": 1
}
];
let idIdx = 1;
const res = head.flatMap((obj) => {
let arr = [];
for (let i = 0; i < obj.times; i )
arr.push({
id: idIdx ,
headId: obj.id,
time: i 1
});
return arr;
});
console.log(res);