Home > Enterprise >  Typescript how to iterate with for loop over object
Typescript how to iterate with for loop over object

Time:10-17

I am writing a Typescript nodejs app where I want to iterate over an incoming sql response but I don't know how to fix the syntax error.

const getTicketPriceBrutto = async (eventID: number): Promise<number> => {
  const rows: [] = await query(
    `SELECT ticketPriceCentBrutto FROM events 
    WHERE eventID = '${eventID.toString()}';`
  );
  let price: number;

  //syntax error...
  // return rows.forEach((element: any) => {
  //   price = element.ticketPriceCentBrutto;
  //   return price;
  // });

  //here is also an syntax error
  for (const iterator of rows) {
    price = iterator.ticketPriceCentBrutto;
  }
  return price;
};

How can this be fixed?

CodePudding user response:

What is the end result you want to get? An array of prices? If yes then use map:

const prices = rows.map((item: any) => item.ticketPriceCentBrutto)

Also your type for rows is syntatically incorrect, it must be an array of something, if you don't know the exact shape of returned objects then use any[] instead of just [], this could also be a reason for invalid syntax

CodePudding user response:

In the commented area you have used forEach to iterate rows array. But forEach doesn't return anything. Here is the correct way to use forEach.

const getTicketPriceBrutto = async (eventID: number): Promise<number[]> => {
  const rows: [] = await query(
    `SELECT ticketPriceCentBrutto FROM events 
    WHERE eventID = '${eventID.toString()}';`
  );
  const priceList: number[] = [];

  for (const row of rows) {
    price.push(row.ticketPriceCentBrutto);
  }
  return priceList;

};

Another option is using the map function provided by javascript.

    const getTicketPriceBrutto = async (eventID: number): Promise<number[]> => {
      const rows: [] = await query(
        `SELECT ticketPriceCentBrutto FROM events 
        WHERE eventID = '${eventID.toString()}';`
      ); 
      return rows.map(row => row.ticketPriceCentBrutto);
};

Both ways you can return an array of prices from getTicketPriceBrutto function

Please check forEach and map for more information.

CodePudding user response:

Something like this?

type Row = { ticketPriceCentBrutto: number };

const getTicketPriceBrutto = async (eventID: number): Promise<number | undefined> => {
    const rows: Row[] = await query(
        `SELECT ticketPriceCentBrutto FROM events 
      WHERE eventID = '${eventID}';`
    );

    return rows[0]?.ticketPriceCentBrutto;
};
  • Related