Home > Back-end >  How to store key and value elements from object in a array inside foreach loop nodejs
How to store key and value elements from object in a array inside foreach loop nodejs

Time:10-15

I am creating dialog flow chatbot to display the list of hotels available from database to the user.

Example:

User:Hi.want to book a hotel.
Bot:Please find the list of hotels below.

0)
hotelname: GrandHyatt
city: Mumbai
price: 100
1)
hotelname: Leelaplace
city: Banglore
price: 110
2)
hotelname: OberaiHotel
city: Mumbai
price: 150
3)
hotelname: Taj Hotel
city: Mumbai
price: 180

//I want to display in this format...

The code below contains the results that I extract from database .Also,I tried to modify the format to display to the user.

    var result=[  //This is the result I get from the database
      {
        Price: 100,
        Availability: 'Yes',
        City: 'Mumbai',
        HotelName: 'GrandHyatt'
      },
      {
        HotelName: 'Leelaplace',
        Price: 110,
        City: 'Banglore',
        Availability: 'Yes'
      },
      {
        HotelName: 'OberaiHotel',
        City: 'Mumbai',
        Availability: 'Yes',
        Price: 150
      },
      {
        HotelName: 'Taj Hotel',
        Availability: 'yes',
        Price: 180,
        City: 'Mumbai'
      }
    ];
    
    var values = [];
    var prices =[];
    for(let i =0;i<result.length;i  )
            {                               
                var hotelname=result[i].HotelName;
                var city=result[i].City;
                var price=result[i].Price;   
                
                
                values.push  ({
                  hotelname: hotelname,
                  city: city,
                  price: price,
                 
            })
            }
             
           let arr=[]
           values.forEach((element, index, array) => {
               console.log(index  ")");
               for (const key in element) {
                    console.log(`${key}: ${element[key]}`); //The results gets displayed as expected
                    
               }
             
            })

Results that gets printed:

0)
hotelname: GrandHyatt
city: Mumbai
price: 100
1)
hotelname: Leelaplace
city: Banglore
price: 110
2)
hotelname: OberaiHotel
city: Mumbai
price: 150
3)
hotelname: Taj Hotel
city: Mumbai
price: 180
 

I get the result printed in the above format as expected .Now,I want to store the "${key}: ${element[key]}" in a variable so that I can pass the variable name to the user like shown below:

df.setResponseText("Please find the details below:" '${key}: ${element[key]}');//This does not work...how can I store and pass as a variable to this.

I tried creating a function and using foreach loop inside the function and am returning the "${key}: ${element[key]}".This also did not work.

I am beginner to Nodejs and figuring out all possibilities.Could you please help me out in this?

CodePudding user response:

I really don't understand your question, but I guess you need to store the option object in a variable not only a key. I don't know if the below code would help.

var result = [
//This is the result I get from the database
{
  Price: 100,
  Availability: "Yes",
  City: "Mumbai",
  HotelName: "GrandHyatt",
},
{
  HotelName: "Leelaplace",
  Price: 110,
  City: "Banglore",
  Availability: "Yes",
},
{
  HotelName: "OberaiHotel",
  City: "Mumbai",
  Availability: "Yes",
  Price: 150,
},
{
  HotelName: "Taj Hotel",
  Availability: "yes",
  Price: 180,
  City: "Mumbai",
},
];

let values = result.map((hotelDetails) => {
  return {
    hotelname: hotelDetails.HotelName,
    city: hotelDetails.City,
    price: hotelDetails.Price,
  };
});

let data = {};
values.forEach((element, index, array) => {
  console.log(index   ")");
  for (const key in element) {
    console.log(`${key}: ${element[key]}`); 
    data[index] = element;
  }
});
console.log(data);

the data object contains your options indexed to be printed

CodePudding user response:

OT: Man, invest in a code formatter because it's really hard to read ...

  1. Why are you breaking building the values array and sending it? You can:
for(let i =0;i<result.length;i  ) {
  //...
  console.log(i ')')
  console.log("hotelname: "  hotelname)
  console.log("city"   result[i].City)
}

  1. Why do you put a value into a variable to add to an array later? Use
values.push  ({
   //...
   city: result[i].City,              
})

Also if you transform variables into objects, and the object key has an identical name as the variable, you can use the short syntax: values.push ({hotelname, city, price})

  1. Why are you processing the result from the database when you can get it ready right away? (Read about SELECT ColumnName AS alias)
  2. Why are you using var? Start using let, 'const' instead. There are quite a lot of context problems with var.
  3. Why aren't you using a unique hotel code from the database? Let 1 hotel disappear/show up for you. And you already have the data mixed up...
  4. Do you see the difference between the apostrophes used?
       console.log(`xx ${key}: ${element[key]}`)
df.setResponseText('xx ${key}: ${element[key]}');

Even the syntax coloring looks different ...

  • Related