We have two arrays that are based on the results of two MySQL SELECT queries, array_1 looks something like this:
JavaScript
x
2
1
[{studentID: "138"}, {studentID: "151"}]
2
And array_2 looks like something this:
JavaScript
1
2
1
[{pacesetterID: “218”}, {pacesetterID: “219”}, {pacesetterID: “221”}, {pacesetterID: “220”}, {pacesetterID: “222”}]
2
I need to end up with a single array where each object in array_1 has a copy of each object in array_2. I.e. each “studentID” gets a copy of every “pacesetterID”. I’ve tried forEach looping, but if array_1 has, let’s say 2 objects, only 2 objects from array_2 are copied.
Both arrays can vary in length, each will have a minimum length of 1 objects but a maximum of anywhere from 40-50 objects.
How can I achieve this? Here is an idea of what I need to achieve based on the two arrays provided:
JavaScript
1
2
1
[{pacesetterID: “218”, studentID: “138”}, {pacesetterID: “219”, studentID: “138”}, {pacesetterID: “221”, studentID: “138”}, {pacesetterID: “220”, studentID: “138”}, {pacesetterID: “222”, studentID: “138”}, {pacesetterID: “218”, studentID: “151”}, {pacesetterID: “219”, studentID: “151”}, {pacesetterID: “221”}, {pacesetterID: “220”, studentID:” 151”}, {pacesetterID: “222”, studentID: “151”}]
2
Advertisement
Answer
It can be done using two loops and saving the result into a third variable.
JavaScript
1
11
11
1
let arr1 = [{studentID: "138"}, {studentID: "151"}];
2
let arr2 = [{pacesetterID: '218'}, {pacesetterID: '219'}, {pacesetterID: '221'}, {pacesetterID: '220'}, {pacesetterID: '222'}];
3
let arr3 = [];
4
5
for(let i=0; i<arr1.length; i++){
6
for(let j = 0; j<arr2.length; j++){
7
arr3.push({arr2[j], arr1[i]});
8
}
9
}
10
11
console.log(arr3);