I'm trying to simplify my codes by using loop
let tmpD = [];
let tmpS0 = [];
let tmpS1 = [];
let tmpS2 = [];
signed = doctors.doc(tmpD[0].key).collection('schedule').get();
signed.then(function(ss){
ss.forEach(function(schedule){
tmpS0.push(schedule.data());
});
console.log(tmpS0)
});
signed = doctors.doc(tmpD[1].key).collection('schedule').get();
signed.then(function(ss){
ss.forEach(function(schedule){
tmpS1.push(schedule.data());
});
console.log(tmpS1)
});
signed = doctors.doc(tmpD[2].key).collection('schedule').get();
signed.then(function(ss){
ss.forEach(function(schedule){
tmpS2.push(schedule.data());
});
console.log(tmpS2)
});
I've tried using for loop like for(var i = 0; i < tmpD.length; i++)
above the first signed and pushed the data to tmpS
and it turns out it pushed everything to a single array. I also tried pushing the array to tmpS[i]
but it caused an error.
You could create a 2D array of tmpS0
, tmpS1
etc and update them based on the index:
let tmpD = [];
let tmpS0 = [];
let tmpS1 = [];
let tmpS2 = [];
let tmps = [tmpS0, tmpS1, tmpS2];
tmpD.forEach(({ key }, i) => {
const signed = doctors.doc(key).collection('schedule').get();
signed.then(function(ss) {
ss.forEach(function(schedule) {
tmps[i].push(schedule.data());
});
console.log(tmps[i])
});
})
Update:
If the variables are dynamic, you can just create the tmpS
array and keep pushing to it based on the index of tmpD
array:
let tmpD = [];
let tmpS = []; // 2D array
tmpD.forEach(({ key }, i) => {
const signed = doctors.doc(key).collection('schedule').get();
signed.then(function(ss) {
tmpS[i] = tmpS[i] || []; // initialize the inner array
ss.forEach(function(schedule) {
tmpS[i].push(schedule.data());
});
console.log(tmpS[i])
});
})
// tmpS will have same number of inner arrays as tmpD.length
console.log(tmpS)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.