How to append table row inside another table when selecting dropdown list in JavaScript?

I have a table that I am creating on button click. When I get my table rows, there is a dropdown on which onchange event is called. So I want to display another row inside parent table when select any of the options from list.

Below is my script where I am creating table:

function searchdata(){
    var companyid = $("#searchQueryDD").val();
    var truckid = $("#searchtruckdd").val();
    var url = "api/gettablebycompanyandtruck";
    $.post(url, {
        companyid : companyid,
        truckid : truckid,
        limit : limit,
    }, function(data, status) {
            if (data.status == "OK") {
                if (data.statusCode == 1) {
                    console.log(data.response);
                    var list = data.response;
                    var row = "";
                    if(list.length > 0){
                        for(var i = 0; i < list.length; i++){
                            row = row + "<tr>" +
                                            "<td>"+list[i].company.companyname+"</td>" +
                                            "<td>"+list[i].driver.username+"</td>" +
                                            "<td>"+list[i].truck.name+"</td>" +
                                            "<td>"+list[i].tripnumber+"</td>" +
                                            "<td><select>" +
                                            "<option selected disabled>Choose subtrip</option><option value='1'>1</option>" +
                                            "<option value='2'>2</option><option value='3'>3</option></select></td>"+
                                            "<td>"+list[i].pickupdate+"</td>" +
                                            "<td>"+list[i].deliverydate+"</td>"+
                                            "<td>"+list[i].loadrate+"</td>" +
                                            "<td>"+list[i].dispatchfee+"</td>" +
                                            "<td>"+list[i].fuel+"</td>" +
                                            "<td>"+list[i].cardfee+"</td>" +
                                            "<td>"+list[i].onroadrepair+"</td>" +
                                            "<td>"+list[i].shoprepair+"</td>" +
                                            "<td>" +
                                                "<a data-toggle='modal' data-target='#mode_payment' onclick="getpayment('"+list[i].tripid+"');">"
                                                    +"<i class='fa fa-paypal' aria-hidden='true' style='color:#3585a5'></i>" +
                                                "</a>" +
                                                "<a onclick="getTrip('"+list[i].tripid+"');">"
                                                    +"<i class='fa fa-pencil-square-o ml-3' style='color: #3384a4;'></i>" +
                                                "</a>" +
                                                "<a href='invoice?id="+list[i].tripid+"'>"
                                                    +"<i class='fa fa-file-pdf-o ml-3' aria-hidden='true' style='color:red'></i>" +
                                                "</a>" +
                                            "</td>" +
                                        "</tr>";
                                    }
                             }
                            document.getElementById('searchresulttable').innerHTML = row;
                } else {
                    var error = data.responseMessage;
                    swal(error, "", "error");
                }
            } else {
                var error = data.responseMessage;
                swal(error, "", "error");
            }
        });
} 

Screenshot to display table row
Screenshot to display dropdown

Map/reduce script not executed correctly (suitescript 2.0)

I am a facing a weird problem where my code (specifically a record.save action) does not seem to be executed. The code is located in the ‘reduce’ phase of a suitescript 2.0 map/reduce script.

I have no clue what the cause for this might be. The logging does display ‘is this executed’ as stated in the example below but the lines below that not seem to be executed. The logging does not show ‘Order lines marked for order with ID:’.

//load the order
    var SOrecord = record.load({
        type: record.Type.SALES_ORDER,
        id: orderId,
        isDynamic: false
    });

     setLineValues(SOrecord, values, newShipmentId)

    log.debug('Is this executed?');
    
    //Save Order
    var recId = SOrecord.save({enableSourcing: false, ignoreMandatoryFields: true});
    
    log.debug('Order lines marked for order with ID: ', recId)
    
    return recId;

Can anyone help?

Thanks in advance!

Print getters when and object is printed in typescript

Is there an option in TypeScript/JavaScript to print an object who has private properties using their getters instead of printing the private properties names.

By example I have this class in TypeScript

class Vehicle {

  constructor(private _brand: string, private _year: number) {}

  get brand(): string {
    return this._brand;
  }

  get year(): number {
    return this._year;
  }

  set year(year: number) {
    this._year = year;
  }

  set brand(brand: string) {
    this._brand = brand;
  }
}

const vehicle: Vehicle = new Vehicle('Toyota', 10);

console.log(vehicle);

I got this

[LOG]: Vehicle: {
  "_brand": "Toyota",
  "_year": 10
} 

But I’m wondering if I can get something like this

[LOG]: Vehicle: {
  "brand": "Toyota",
  "year": 10
} 

Amount counter works only on first product

I have a problem with using javascript with SQL.
It looks like this that I have few items that appears on the screen, they appears from SQL database, and the code looks like shown. Bascially if I have more than one product that is shown on the website, only first one works as it should. Any solutions?

let displayAddCounter = document.querySelector("#add_count_cart");
let displayRemoveCounter = document.querySelector("#remove_count_cart");
let displayCounter = document.querySelector("#amount_count_cart");

var x = 0;

displayAddCounter.addEventListener("click", function(){
    if(x < 10){
    x++;
    displayCounter.innerHTML = x;
  } else {
    alert("If you want to buy more than 10, please contact our support! We will gladly help you :)")
  }
});

displayRemoveCounter.addEventListener("click", function(){
  if(x == 0){
    displayCounter.innerHTML = x;
  } else {
    x--;
    displayCounter.innerHTML = x;
  }
  
});

let buttonCartAdd = document.getElementById("btn_add_to_cart");
let itemName = document.querySelector(".product_name");

buttonCartAdd.addEventListener("click", function(){
    if(x == 0){
        alert("Please choose amount of items!");
    }
    else if(x > 0){
        alert("You added " + x + itemName.innerHTML + " to the cart!");
    }
  
});
 <?php
    $sql = "SELECT * FROM products";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        ?>
        <div class="product_card col-lg-4 col-md-6 col-sm-12 mb-4 box-shadow">
          <div class="card-header">
            <h3 class="product_name my-0 font-weight-light"> <?php echo $row["productName"]?> </h3>
          </div>
          <div class="card-body">
            <h2 class="card-title pricing-card-title"> </h2>
            <img class="pic" src="productsImages<?php echo $row["productID"];?>.jpeg" height="150px" width="120px"></img>
            <br>
            <p>
            <?php echo $row["productPrice"];?> SEK
            </p>
            <div class="row amount_counter">
              <button id="remove_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> - </button>
              <div id="amount_count_cart" class="btn col-6 col border-top border-bottom dark rounded h-75">
              0
              </div>
              <button id="add_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> + </button>
              <button id="btn_add_to_cart" class="btn btn-lg btn-outline-success col-lg-8 col-md-12 col offset-lg-2"> Add <i type="button" class="fas fa-cart-plus"></i></button>
            </div>
          </div>
        </div>
      <?php
    }
    } else {
        echo "0 results";
    }
    $conn->close();
    ?>

How do I get a value from a listbox instead of a textbox, my code is as follows

I’m trying to make a program that shows the prime numbers of the numbers added to the listbox from the textbox and then written in the listbox, with a message box, can anyone help me, where am I wrong?

private void button2_Click(object sender, EventArgs e)

` int deneme = 0;
int sayilarim = Convert.ToInt32(textBox1.Text);

                for (int i = 2; i < sayilarim; i++)
                {
                    if (sayilarim % i == 0)
                        deneme++;
                }
                if (deneme != 0)
                {                       listBox1.Items.Add(textBox1.Text + " Asal Sayi değildir.");
                    MessageBox.Show("Bu Bir Asal Sayi Değildir.");
                }
                else
                {
                    listBox1.Items.Add(textBox1.Text + " sayidir.");
                    MessageBox.Show("Bu Bir Asal Sayi.");
                }
                textBox1.Clear();
            }                MessageBox.Show(listBox1.Items.Count.ToString() + " Adet asal sayı var.");`

Background issue when opening menu in laravel

I am having background issue when opening menu in Laravel. Exactly what I want to do is actually the menu in the example below.

When opening the menu with Ajax, the background is also opened. I can’t turn off the background while the menu is closing 🙁

thank you all

sample : https://www.envelopes.com/

        $('.category-nav-element').each(function (i, el) {
        $(el).on('mouseover', function (e) {
            e.preventDefault();
            if (!$(el).find('.sub-cat-menu').hasClass('menuShow')) {
                $.ajax({
                    url: '{{ route('category.elements') }}',
                    method: "POST",
                    data: {
                        "_token": "{{ csrf_token() }}",
                        "id": $(el).data('id')
                    },
                    success: function (html_content) {
                        $(el).find('.sub-cat-menu').addClass('menuShow').html();
                        $(el).find('.sub-cat-menu').addClass('menuShow').html(html_content);
                        $(".menu_overlay").css("display", 'block');
                    }
                });
            }
        });
    });

How to remove added classes from an element in reactjs

I am making a drag n drop sort of game where you match the logos with their corresponding name.

If user matches the logo with the name correctly than the field which you could drop the logo gets additional classes.

Like this:

if (isCorrectMatching) {
      
      
      event.target.classList.add('dropped');
      draggableElement.classList.add('dragged');
      event.target.classList.add('dragged');
      event.target.setAttribute('draggable', 'false');
      draggableElement.setAttribute('draggable', 'false');
      event.target.innerHTML = `<i class="fab fa-${draggableElementBrand}" style="color: ${draggableElement.style.color};"></i>`;
}
  

If every match is found user can go to next level , my problem is that these additional classes are staying there , how do I remove them ?

I am mapping them out like this:

 <div className='containerItems'>
        {draggableItems.map((x,i) => {
          return (
            <div className='draggable-items'>
              <i
                onDragStart={(e) => dragStart(e)}
                className={`draggable fab fa-${x}`}
                id={x}
                draggable='true'
                ref={draggableOnes.current[i]}
              ></i>
            </div>
          );
        })}
      </div>

      {matchingPairs.map((x,i) => {
        return (
          <section className='matching-pairs'>
            <div className='matching-pair'>
              <span className='label'>{x}</span>
              <span
                className='droppable'
                // ref={droppableOnes.current[i]}
                onDragEnter={(e) => dragEnter(e)}
                onDragOver={(e) => dragOver(e)}
                onDragLeave={(e) => dragLeave(e)}
                onDrop={(e) => drop(e)}
                data-brand={x}
              ></span>
            </div>
          </section>
        );

I can not seem to solve this one, like how do I remove all the classes that I’ve added when there was a correct matching.

I would like to remove basically everything that I’ve added in my if (isCorrectMatching) .

I’ve tried to use refs but it did not work. What is the way to go for this?

Is there a way to create variables for react hooks at runtime

Is there a way to create variables for react hooks at runtime, so that the value of variables can be extracted and passed to an API at runtime as against having specific variable names created at design time the way I am currently doing it

See my code below

import React, { FC, useState } from "react"
import { View, SafeAreaView, TextInput, ImageBackground, ScrollView, Alert } from "react-native"
import { StackScreenProps } from "@react-navigation/stack"
import { observer } from "mobx-react-lite"
import { Button, Text } from "../../components"
import { NavigatorParamList } from "../../navigators"
import { Images } from "../../config"
import { store } from "../../store"
import { RadioButton } from "react-native-paper"
import axios from "axios"
import { SEND_FEEDBACK_URL, showErrorAlert } from "../../utils/constants"
import {
  BOTTOM_HALF,
  CONTINUE,
  CONTINUE_TEXT,
  FOOTER_CONTENT,
  FULL,
  LABEL,
  RED_ACTION_LINK,
  RED_ACTION_STYLES,
  REGULAR_TEXT,
  SMALLL_TEXT,
  SMALLL_TEXT_C,
  SUBJECT,
  textArea,
  textAreaContainer,
} from "./send-feedback-styles"

export const SendFeedbackScreen: FC<StackScreenProps<NavigatorParamList, "Send">> = observer(
  ({ navigation }) => {
    const tempQuestIdArray = []
    let tempStr: string,
      temp0: string,
      temp1: string,
      temp2: string,
      temp3: string,
      temp4: string,
      temp5: string,
      temp6: string,
      temp7: string
    const [freeText, setFreeText] = useState("")

    console.log("<<<<<<BEFORE fetching stored token")
    const token = store.getState().token.tokenValue
    console.log("<<<<<<<PROFILE TOKEN>>>>>>>>>")
    console.log(JSON.stringify(token))
    console.log("<<<<<<<PROFILE TOKEN>>>>>>>>>")
    console.log("<<<<<<BEFORE fetching stored Sales Agent Id")
    const salesAgentId = store.getState().salesAgentId.salesAgentIdValue
    console.log("<<<<<<< SALES Agent id >>>>>>>>>")
    console.log(JSON.stringify(salesAgentId))
    console.log("<<<<<<< SALES Agent id >>>>>>>>>")

    const getSuccessScreen = () => navigation.navigate("Successful")

    const config = {
      headers: { Authorization: `bearer ${token}` },
    }

    const api = axios.create({
      baseURL: SEND_FEEDBACK_URL,
    })

    const [checked0, setChecked0] = useState("")
    const [checked1, setChecked1] = useState("")
    const [checked2, setChecked2] = useState("")
    const [checked3, setChecked3] = useState("")
    const [checked4, setChecked4] = useState("")
    const [checked5, setChecked5] = useState("")
    const [checked6, setChecked6] = useState("")
    const [checked7, setChecked7] = useState("")
    const [questIdStore, setQuestIdStore] = useState([])

    // const { setToken } = useTokenStore()
    const barcodeId = store.getState().barcodeId.barcodeIdValue
    const CustomerId = store.getState().customerId.customerIdValue
    const DeviceId = store.getState().deviceId.deviceIdValue
    const questionsArray = store.getState().questionArray.questionArrayValue
    const CustomerName = store.getState().customerName.customerNameValue

    const QUESTIONS = questionsArray
    console.log("questions  >> ", QUESTIONS)
    // console.log("QUESTIONS[0].id  >> ", QUESTIONS[0].id)

    const renderInputRadios = () => {
      const qArray = QUESTIONS
      return (
        <View>
          {qArray.map((i, key) => {
            console.info("key >>> ", key)
            console.info("i.id >>> ", i.id)
            tempQuestIdArray.push(i.id)
            // setQuestIdStore(tempQuestIdArray) --causing re renders
            // eslint-disable-next-line no-eval
            tempStr = eval("checked" + key)
            console.info("tempQuestIdArray >>> ", tempQuestIdArray)

            switch (key) {
              case 0:
                temp0 = tempStr
                console.info("temp0 >>> ", temp0)
                break
              case 1:
                temp1 = tempStr
                console.info("temp1 >>> ", temp1)
                break
              case 2:
                temp2 = tempStr
                console.info("temp2 >>> ", temp2)
                break
              case 3:
                temp3 = tempStr
                console.info("temp3 >>> ", temp3)
                break
              case 4:
                temp4 = tempStr
                console.info("temp4 >>> ", temp4)
                break
              case 5:
                temp5 = tempStr
                console.info("temp5 >>> ", temp5)
                break
              case 6:
                temp6 = tempStr
                console.info("temp6 >>> ", JSON.stringify(temp6))
                break
              case 7:
                temp7 = tempStr
                console.info("temp7 >>> ", JSON.stringify(temp7))
                break
              default:
                console.info("INSIDE DEFAULT")
            }
            return (
              <View key={key}>
                <View style={RED_ACTION_STYLES}>
                  <View>
                    <Text style={SMALLL_TEXT}>{i.questionWord}</Text>
                  </View>
                  <View style={RED_ACTION_LINK}>
                    <Text style={SMALLL_TEXT_C}>1</Text>
                    <RadioButton
                      value="0"
                      status={tempStr === "0" ? "checked" : "unchecked"}
                      onPress={() =>{
                        switch (key) {
                          case 0:
                            setChecked0("0")
                            break
                          case 1:
                            setChecked1("0")
                            break
                          case 2:
                            setChecked2("0")
                            break
                          case 3:
                            setChecked3("0")
                            break
                          case 4:
                            setChecked4("0")
                            break
                          case 5:
                            setChecked5("0")
                            break
                          case 6:
                            setChecked6("0")
                             break
                          case 7:
                            setChecked7("0")
                             break
                          default:
                            console.info("INSIDE DEFAULT")
                        }
                      }
                      
                      }
                    />
                    <Text style={SMALLL_TEXT_C}>2</Text>
                    <RadioButton
                      value="1"
                      status={tempStr === "1" ? "checked" : "unchecked"}
                      onPress={() =>{
                        switch (key) {
                          case 0:
                            setChecked0("1")
                            break
                          case 1:
                            setChecked1("1")
                            break
                          case 2:
                            setChecked2("1")
                            break
                          case 3:
                            setChecked3("1")
                            break
                          case 4:
                            setChecked4("1")
                            break
                          case 5:
                            setChecked5("1")
                            break
                          case 6:
                            setChecked6("1")
                             break
                          case 7:
                            setChecked7("1")
                             break
                          default:
                            console.info("INSIDE DEFAULT")
                        }
                      }
                      
                      }
                    />

                    <Text style={SMALLL_TEXT_C}>3</Text>
                    <RadioButton
                      value="2"
                      status={tempStr === "2" ? "checked" : "unchecked"}
                      onPress={() =>{
                        switch (key) {
                          case 0:
                            setChecked0("2")
                            break
                          case 1:
                            setChecked1("2")
                            break
                          case 2:
                            setChecked2("2")
                            break
                          case 3:
                            setChecked3("2")
                            break
                          case 4:
                            setChecked4("2")
                            break
                          case 5:
                            setChecked5("2")
                            break
                          case 6:
                            setChecked6("2")
                             break
                          case 7:
                            setChecked7("2")
                             break
                          default:
                            console.info("INSIDE DEFAULT")
                        }
                      }
                      
                      }
                    />
                    <Text style={SMALLL_TEXT_C}>4</Text>
                    <RadioButton
                      value="3"
                      status={tempStr === "3" ? "checked" : "unchecked"}
                      onPress={() =>{
                        switch (key) {
                          case 0:
                            setChecked0("3")
                            break
                          case 1:
                            setChecked1("3")
                            break
                          case 2:
                            setChecked2("3")
                            break
                          case 3:
                            setChecked3("3")
                            break
                          case 4:
                            setChecked4("3")
                            break
                          case 5:
                            setChecked5("3")
                            break
                          case 6:
                            setChecked6("3")
                             break
                          case 7:
                            setChecked7("3")
                             break
                          default:
                            console.info("INSIDE DEFAULT")
                        }
                      }
                      
                      }
                    />
                    <Text style={SMALLL_TEXT_C}>5</Text>
                    <RadioButton
                      value="4"
                      status={tempStr === "4" ? "checked" : "unchecked"}
                      onPress={() =>{
                        switch (key) {
                          case 0:
                            setChecked0("4")
                            break
                          case 1:
                            setChecked1("4")
                            break
                          case 2:
                            setChecked2("4")
                            break
                          case 3:
                            setChecked3("4")
                            break
                          case 4:
                            setChecked4("4")
                            break
                          case 5:
                            setChecked5("4")
                            break
                          case 6:
                            setChecked6("4")
                             break
                          case 7:
                            setChecked7("4")
                             break
                          default:
                            console.info("INSIDE DEFAULT")
                        }
                      }
                      
                      }
                    />
                  </View>
                </View>
              </View>
            )
          })}
          <View style={textAreaContainer}>
            <TextInput
              style={textArea}
              underlineColorAndroid="transparent"
              placeholder="Type something"
              placeholderTextColor="grey"
              numberOfLines={5}
              multiline={true}
              value={freeText}
              onChangeText={(freeText) => setFreeText(freeText)}
            />
          </View>
        </View>
      )
    }

    const onSendFeedbacck = async () => {
      if (!checked1) {
        showErrorAlert("Your Response")
        return
      }
      if (!checked2) {
        showErrorAlert("Your Response")
        return
      }
      if (!checked3) {
        showErrorAlert("Your Response")
        return
      }

      console.log("<<< inside onSendFeedbacck >>>>>")

      const quest1: string = QUESTIONS[0].id
      const quest2: string = QUESTIONS[1].id
      const quest3: string = QUESTIONS[2].id  
      const quest4: string = QUESTIONS[3].id
      const quest5: string = QUESTIONS[4].id
      const quest6: string = QUESTIONS[5].id
      const quest7: string = QUESTIONS[6].id

      // const salesAgentId = LOCAL_SALES_AGENT_ID

      console.log("quest1 ..>>>>>>>> ", quest1)
      console.log("quest2 ..>>>>>>>> ", quest2)
      console.log("quest3 ..>>>>>>>> ", quest3)
      console.log("quest4 ..>>>>>>>> ", quest4)
      console.log("quest5 ..>>>>>>>> ", quest5)
      console.log("quest6 ..>>>>>>>> ", quest6)
      console.log("quest7 ..>>>>>>>> ", quest7)

      const answer1 = {
        questionId: quest1,
        answer: Number(checked0),
      }

      const answer2 = {
        questionId: quest2,
        answer: Number(checked1),
      }
      const answer3 = {
        questionId: quest3,
        answer: Number(checked2),
      }
      const answer4 = {
        questionId: quest4,
        answer: Number(checked3),
      }
      const answer5 = {
        questionId: quest5,
        answer: Number(checked4),
      }
      const answer6 = {
        questionId: quest6,
        answer: Number(checked5),
      }
      const answer7 = {
        questionId: quest7,
        answer: Number(checked6),
      }

      const AnswerArray = []

      AnswerArray.push(answer1)
      AnswerArray.push(answer2)
      AnswerArray.push(answer3)
      AnswerArray.push(answer4)
      AnswerArray.push(answer5)
      AnswerArray.push(answer6)
      AnswerArray.push(answer7)

      console.log("AnswerArray ..>>>>>>>> ", AnswerArray)

      const AnswerArrayStr = JSON.stringify(AnswerArray)
      console.log("AnswerArrayStr ..>>>>>>>> ", AnswerArrayStr)

      const AnswerArrayObj = JSON.parse(AnswerArrayStr)
      console.log("AnswerArrayObj ..>>>>>>>> ", AnswerArrayObj)

      const dataToSend = {
        customerId: CustomerId,
        productDeviceId: DeviceId,
        questions: AnswerArrayObj,
        otherComments: freeText,
        salesAgentId: salesAgentId,
      }

      console.log("dataToSend ..>>>>>>>> ", dataToSend)
      try {
        console.log("<<<<<<<BEFORE RESPONSE FOR SEND FEEDBACK >>>>>>>>>")
        console.log("dataToSend >> ", dataToSend)
        console.log("config >> ", config)

        const res = await api.post("/", dataToSend, config)
        console.log(res)
        console.log("Res >> ", res)
        console.log("<<<<<<<AFTER RESPONSE FOR SEND_FEEDBACK_URL >>>>>>>>>")

        // eslint-disable-next-line no-prototype-builtins
        if (res.hasOwnProperty("data")) {
          // Get Response
          getSuccessScreen()
        } else {
          console.log("<<<<<<<ERRRRRROR>>>>>>>>>")
        }
      } catch (err) {
        console.log(err)
        Alert.alert("Error " + err)
      }
    }

    return (
      <ImageBackground source={Images.bg} style={FULL}>
        <ScrollView showsVerticalScrollIndicator={false} showsHorizontalScrollIndicator={false}>
          <View style={BOTTOM_HALF}>
            <SafeAreaView>
              <Text style={SUBJECT}>Device Identified</Text>

              <View>
                <Text style={LABEL}>Barcode ID</Text>
                <Text style={REGULAR_TEXT}>{barcodeId}</Text>
              </View>

              <View>
                <Text style={LABEL}>Customer </Text>
                <Text style={REGULAR_TEXT}>{CustomerName}</Text>
              </View>

              <View>
                <Text style={LABEL}>
                  Please Fill the Form Below to Provide More Information on This Device{" "}
                </Text>
              </View>

              {renderInputRadios()}

              <View style={FOOTER_CONTENT}>
                <Button
                  testID="next-screen-button"
                  style={CONTINUE}
                  textStyle={CONTINUE_TEXT}
                  tx="inside.send_feedback"
                  onPress={onSendFeedbacck}
                />
              </View>
            </SafeAreaView>
          </View>
        </ScrollView>
      </ImageBackground>
    )
  },
)

You can see from my code above that I am creating an array of temporary radio button values from user inputs but I am unable to get the result of the user actions

You can also see that I am creating temporary variables objects for answer1 to answer7. This limits the component results to just seven

Thats against the requirement

Is there a way around this

Thanks

I need to store bootstrap 4 card data in javascript.Not for a sing card but six with the help of loops.I think accessing an item using indexes is old

I have six a bootstrap4 card which are assigned same class name.When accessing the card information such as card title it returns an array of objects for the six card, the same occurs when am accessing the card body.My aim is to be able to individual title,and body for that specific card.But then I need to be able to do this for the six cards without having to repeat the code. ie I need to do this with help of loops.I have a empty array to store individual card data

How to map and create a new Array out of 2 arrays?

I have an array, grpList contains unique id’s & unique names.

grpList = [
  { name: "grp1", id: "1" },
  { name: "grp2", id: "2" },
  { name: "grp3", id: "3" },
  { name: "grp4", id: "4" },
  { name: "grp5", id: "5" },
  { name: "grp6", id: "6" }
]

Another type of Array, In the below array currentList, it has only 2 types i.e G or Q, with type 'G' it has array values with unique names. These names are mapped from the grpList Array.

currentList = [
  { name: "name1", type: "G", values: ["grp1", "grp3"] },
  { name: "name2", type: "Q", values:"abcd" },
  { name: "name3", type: "G", values: ["grp1", "grp5"] },
  { name: "name4", type: "Q", values:"frd" },
  { name: "name5", type: "G", values: ["grp1", "grp2"] },
  { name: "name6", type: "Q", values:"erer" }
]

Now What I want is that create a new array that consist data of type currentList i.e it should contains properties of currentList array and it should mapped with ids corresponding to grpList array.

Example:

newArry = [
      { name: "name1", type: "G", values: ["1", "3"] },
      { name: "name2", type: "Q", values:"abcd" },
      { name: "name3", type: "G", values: ["1", "5"] },
      { name: "name4", type: "Q", values:"frd" },
      { name: "name5", type: "G", values: ["1", "2"] },
      { name: "name6", type: "Q", values:"erer" }
]

Webpack: Uncaught ReferenceError: process is not defined when importing Js files

After adding a few extra JavaScript entry files to Webpack it has broken the configuration. I basically added this line navbar: './src/navbar.js', to my config file.

I then import the navbar.js into my index.js file :
import navbar from './navbar.js';

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    index: './src/index.js',
    firstLoad: './src/firstLoad.js',
    navbar: './src/navbar.js',
  },

  // resolve: {
  //   fallback: {
  //     util: require.resolve("util/")
  //   }
  // },

  devtool: 'inline-source-map',

  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),
  ],

  output: {

    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  module: {
    rules: [
        {
            test: /.s[ac]ss$/i,
            use: [
                // Creates `style` nodes from JS strings
                "style-loader",
                // Translates CSS into CommonJS
                "css-loader",
                // Compiles Sass to CSS
                "sass-loader",
            ],
       },
    ],
  }
};

I’ve tried this solution but it hasn’t resolved the issue.
Solution

Making a page for each category to show restaurants

I am making a category page for restaurants and I have 2 Json files. One with information about the restaurants and one for the categories.

This is the restaurants.Json file which includes the categories for this restaurant:

{
  "restaurants": [
    {
      "name": "Grill",
      "id": "120dxpx5",
      "slogan": "Best burgers in the town",
      "createdDate": "2019-01-01",
      "openingHours": [
        {
          "days": "Monday - Friday",
          "hours": "09:00 - 17:00"
        },
      ],
      "website": "http://website.lt",
      "categories": ["Burger", "Salads", "Grill"]
    },
    {...},

And this is categories.json with all of the available categories:

    {
  "categories": [
    "Burger",
    "Salads",
    "Grill",
    "Ramen",
    "Sandwich",
    "Kebab",
    "Pizza",
    "Brunch",
    "Pancakes",
    "Sushi",
    "Sweets",
    "Soups",
    "Donuts",
    "Hot dogs"
  ]
}

This is my code Category.js:

import React, { useState, useEffect } from "react";
import RestaurantCard from "components/restaurantCard";
import "./category.scss";

const Category = () => {
  const categoryUrl =
    "categories.json";
  const restaurantsUrl =
    "restaurants.json";

  const [categoryRestaurants, setCategoryRestaurants] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const restaurantsResponse = await fetch(restaurantsUrl);
        const restaurantsJson = await restaurantsResponse.json();
        const restaurants = restaurantsJson.restaurants;

        const categoryResponse = await fetch(categoryUrl);
        const categoryJson = await categoryResponse.json();
        const [categories] = categoryJson.categories;

        const restaurantWithCategory = restaurants.categories;
        const filteredRestaurant = restaurants.filter((categories) =>
          restaurantWithCategory.includes(categories)
        );
        setCategoryRestaurants(filteredRestaurant);
      } catch (error) {}
    };

    fetchData();
  }, []);

  <div className="category">
    <h1 className="h1-font category__header">
      The best place for the "category" !
    </h1>
    {categoryRestaurants.slice(0, 2).map((categories) => {
      return <RestaurantCard key={restaurant.id} restaurant={categories} />;
    })}
  </div>;
};

export default Category;

How could I create a page for each of the categories above and show each restaurant which has the category in it’s json file.

Algolia instantsearch.js api doesn’t display the data on dropdown

Algolia’s InstantSearch.js is working really great. (not on mine)

However, I created a custom API which has some restaurant information in it.

I’d like to understand why I don’t get the result displayed of the API on the dropdown.
I followed step by step and the api data are correct.

What am I missing here?

https://codesandbox.io/s/compassionate-goodall-39hhj?file=/src/app.js

/* global instantsearch algoliasearch */

const search = instantsearch({
  indexName: 'demo_ecommerce',
  searchClient: algoliasearch('XYTOW5OR7C', 'f446bfff654badd2f52e813e44e52518'),
});

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchbox',
  }),

  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item: `
        <div>
          <img src="{{foodimage}}" align="left" alt="{{restaurantname}}" />
          <img src="{{restaurantlogo}}" align="left" alt="{{restaurantname}}" />
          <div class="hit-name">
            {{restaurantname}}{ "attribute": "restaurantname" }{{restaurantname}}
          </div>
          <div class="hit-description">
            {{restauranttype}}{ "attribute": "restauranttype" }{{restauranttype}}
          </div>
          <div class="hit-rate">${{rate}}</div>
          <div class="hit-review">${{review}}</div>
          <div class="hit-offer">${{offer}}</div>
          <div class="hit-delivery">${{delivery}}</div>
          <div class="hit-location">${{location}}</div>
        </div>
      `,
    },
  }),
]);

search.start();

How to set a stream for a specific user with mongodb streams

I am trying to set up a mongodb stream for a specific user but the thing is that you won’t be able to know what someone will give as a username, in this case the field is called: charactername.

For this project I am using: mongodb, express, nodejs and socket.io. The socket.io broadcasts it to the frontend and refreshed the page once there is a change in the database. But the thing is right now if something is changed in the collection “users” the refresh happens for every user instead of a specific user of whose document gets updated.

This is the code for the backend:

User.watch([{ $match: {
operationType: 
{$in: ['update']},
"updateDescription.updatedFields.charactername": ""   //What should I put here ?
}}]).
on('change', data => {
  console.log('Update action triggered');
  console.log(new Date(), data.updateDescription.updatedFields);
  console.log(data)
  io.emit("DBchange", data);
});

This is the code for the front end:

<script>

socket.on("DBchange", (data) => {
console.log(data)
location.reload()
});

</script>

How can I fix this issue?