Home > Blockchain >  Converting a for loop function results into an array
Converting a for loop function results into an array

Time:01-29

I am looping through an array of selected index comparing each value to a database of machine pricing, and returning the price of each selected index. the problem is, the result repData1 return individual results, I want those resuls to displayed in an array for I can manipulate the array. I have tried push, concat.... string results is displayed for each item rather than a whole.

for (let a = 0; a < selectedindex.length; a  ) {
  wixData
    .query('MachinePricing')
    .contains('title', selectedindex[a])
    .find()
    .then(async (results) => {
      if (results.items.length > 0) {
        let repData = results.items;
        let repData1 = repData.map(({ prices }) => prices);
        console.log(repData1);
      }
    });
}

CodePudding user response:

Don't loop async calls using iterators

Instead do this

const a = 0
const repData = [];

function getData = () => {
  if (a >= selectedindex) {
    processRepData();
    return;
  }
  wixData
    .query('MachinePricing')
    .contains('title', selectedindex[a])
    .find()
    .then(results => {
      if (results.items.length > 0) {
        repData.concat(results.items.map(({prices}) => prices));
      }
      a  ;
      getData()
    });
}    
getData()

CodePudding user response:

I think what you are doing is this (run a query for each selected index and extract the returned prices into an array):

const queries = selectedindex.map(ix =>  wixData
    .query('MachinePricing')
    .contains('title', ix)
    .find())
const results = await Promise.all(queries)
const prices = results.flatMap(r => r.items.map(i => i.prices))
  • Related