So I'm trying to generate an array that will have multiple objects, one of them with another array. Each object should have its own unique id, but when using for loop, each batch has objects with the same repeated ids. using i variable or even adding random number value seems to be not working. Is this even achievable in javascript?
Test.js
const testFunc = () => {
let resultArray = []
let testObj = {}
let testArray = []
const rn = () => {
return ~~(Math.random() * 1000)
}
for (let i = 0; i < 3; i++) {
testObj = { id: rn() }
testArray.push(testObj)
testObj = {}
}
for (let i = 0; i < 3; i++) {
resultArray.push(testArray)
}
console.log(resultArray)
return resultArray
}
Expected result:
[
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
],
[
{ id: 681, text: 0 },
{ id: 384, text: 1 },
{ id: 413, text: 2 },
{ id: 721, text: 3 },
{ id: 985, text: 4 }
],
[
{ id: 348, text: 0 },
{ id: 911, text: 1 },
{ id: 255, text: 2 },
{ id: 816, text: 3 },
{ id: 797, text: 4 }
]
]
Result I get:
[
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
],
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
],
[
{ id: 859, text: 0 },
{ id: 232, text: 1 },
{ id: 240, text: 2 },
{ id: 638, text: 3 },
{ id: 393, text: 4 }
]
]