How to syntactically use pattern in javascript with match method?

I aim at using specific pattern to check user inputs in a form and to be honest I am a beginner in javascript and not used to javascript syntax since I recently realised I would need it for my code.
More specifically my issue is the use of patterns. I went on regexr.com that gives patterns code and make you able to create your own. On there I took already existing ones for passwords (for the password it’s at least 8 characters 1 uppercase 1 lowercase and 1 number) and emails. And on regexr.com the Password Rockyh12 for example match the pattern but when I add it to my website, it says it doesn’t meet the password requirements. I think it is my way of putting the patterns in javascript the problem

if(!password.value.match(pattern="^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$)"))

The html code for the site

<form>
    <div class="tab tab-1 active"><h3 class="infos">Credentials</h3>
        <p>
            <label ">Email address&nbsp;<span class="required" >*</span></label>
            <input type="text" autocomplete="email" name="email" id="reg_email" value="" required />
        <div id="email_validation" style="color: red;></div>
        </p>



        
            <p>
                <label for="reg_password">Password&nbsp;<span class="required">*</span></label>
                <input type="text" name="password" id="reg_password" autocomplete="new-password" required />
                <div id="password_validation" style="color: red;"></div>
            </p>
                <br>
            
        
        

    <div class="next-0 next">
        <button type="button" name="next_1">Next</button>
    </div>
    <div class=""></div>

    </div>
</form>

and the javascript is here:

//--------EMAIL CHECK--------------------------------------------------------------------------------------------------------------------

const email = document.querySelector('input[name="email"]');
    var emailValidation = document.getElementById('email_validation');

    email.addEventListener("focus", (event) => {


         if(!email.value.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/)){
           emailValidation.innerHTML="Please enter a valid email address";
           return false;
        }

        else{
            return true;
        }
});

email.addEventListener("keyup", (event) => {
    
    if(!email.value.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/)){
      emailValidation.innerHTML="Please enter a valid email address";
      return false;
   }else {
    emaildValidation.innerHTML="";
    event.target.style.borderColor = "green";
       return true;
   }
});
//---------------------------------------------------------------------------------------------------------------------------------------------






// ------PASSWORD CHECK-----------------------------------------------------------------------------------------------------------------
    const password = document.querySelector('input[name="password"]');
    var passwordValidation = document.getElementById('password_validation');

    password.addEventListener("focus", (event) => {
    
         if(!password.value.match(pattern="^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$)")){
           passwordValidation.innerHTML="Password must be at least 8 character and contain 1 uppercase,1 lowercase and 1 number";
           return false;
        }

        else{
            return true;
        }
});

password.addEventListener("keyup", (event) => {
    
    if(!password.value.match(pattern="^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$")){
      passwordValidation.innerHTML="Password must be at least 8 character and contain 1 uppercase,1 lowercase and 1 number";
      return false;
   }else {
    passwordValidation.innerHTML="";
    event.target.style.borderColor = "green";
       return true;
   }
});
//-----------------------------------------------------------------------------------------------------------------------------------------

I have tried deleting the brackets around the pattern code and “pattern” leaving it like this

if(!password.value.match(^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$))

still I don’t know what pattern it has been set to but it still don’t work.

How do I keep my canvas at the max dimensions it can fill in the window without causing a scroll bar, and maintain the aspect ratio I set?

I am trying to make a canvas game, and I’d like the canvas to be responsive to different window sizes. I also would like the canvas/assets to keep a 3:2 aspect ratio. There is some unexpected behavior from the canvas when adjusting the size; there is a scroll bar even though I have set the max-height, and also it seems like the canvas zooms in when resizing at smaller sizes, but really I want all parts of the canvas visible.

here is my index.html:

    <div class="canvas-container">
        <canvas></canvas>
    </div>
    <script src="./script.js"></script>

here is my styles.css

* {
    box-sizing: border-box;
}

html,
body {
    margin: 0;
    height: 100vh;
}

body {
    display: flex;
    align-items: center;
    justify-content: center;
}


.canvas-container {
    margin: 0 auto;
    width: 100%;
    max-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;

}

canvas {
    margin: 0 20px;
    width: 100%;
}

here is my script.js:

const body = document.querySelector('body');
const canvasContainer = document.querySelector('.canvas-container');
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const defaultCanvasWidth = canvas.width = 3 * window.innerHeight / 2;
const defaultCanvasHeight = canvas.height = window.innerHeight;



function restrainCanvasHeightToWindowHeight(canvas) {
    const maxHeight = window.innerHeight;

    if (canvas.height > maxHeight) {
        canvas.style.height = maxHeight;
        defaultCanvasWidth;
    }
}



class Entity {
    constructor({position}, img) {
            this.position = position;
            this.img = img;
    }

    draw() {
        ctx.beginPath();
        ctx.fillStyle = this.img;
        ctx.fillRect(this.position.x, this.position.y, 100, 100);
    
    }

}

  

const machine = new Entity({position: { x: 0, y: 0 } }, 'green');


//set background to see canvas
ctx.fillStyle = 'red';  
ctx.fillRect(0, 0, canvas.width, canvas.height);


machine.draw();


I have tried several different approaches to the resizing function, setting the canvas size based off width first, then based off height instead, messing with the container in CSS to contain the canvas, but nothing I’ve tried works other than hard coding a max-width in px to be a number that would allow the height 3:2 ratio to be smaller than the height of the window on my device… but I want it to be dynamic not fixed.

if you have any suggestions please let me know, thank you

Implementation of Flood fill Algo in javaScript by changing color of grid having similar color

I have already initialize my each node color, I am trying to change the color to selectedColor of all nodes having similar color using flood fill but instead of that it changes all the color present in that maze

enter image description here

var selectedColor = 'rgb(255, 255, 255)'; 
var storedColor;

function setup(){
    var maze_container = document.getElementById('maze_container');

    for(var i =0 ; i< 10 ; i++){
        var row = document.createElement('div');
        row.className = 'row row' + (i+1);
        row.id = 'row' +(i +1);
        for(var j =0 ; j< 10 ; j++){
            var node = document.createElement('div');
            node.className = 'node node' + ((i*10)+(j+1));

            node.id = 'node' + ((i*10)+(j+1));

            // Add click event listener to each node
            node.addEventListener('click', function() {
                storedColor = this.style.backgroundColor;
                changeColorAndFloodFill(this);
            });

            row.appendChild(node);
        }

        maze_container.appendChild(row);
    }
}

// Function to change color of clicked node and perform flood fill
function changeColorAndFloodFill(node) {
    // If the stored color is not the selected color, change the color of the node
    if (storedColor !== selectedColor) {
        node.style.backgroundColor = selectedColor;

        // Perform flood fill algorithm from the clicked node
        floodFill(node);
    }
}

// Function to perform flood fill algorithm
function floodFill(node) {
    // Get the neighboring nodes of the clicked node
    var neighbors = getNeighbors(node);

    // For each neighboring node, if it is not already the selected color,
    // change its color and recursively perform flood fill from that node
    neighbors.forEach(function(neighbor) {
        var neighborColor = neighbor.style.backgroundColor;
        if (neighborColor !== selectedColor) {
            neighbor.style.backgroundColor = selectedColor;
            floodFill(neighbor);
        }
    });
}

// Function to get the neighboring nodes of a given node
function getNeighbors(node) {
    var nodeID = parseInt(node.id.replace('node', ''));
    var neighbors = [];

    // Get the IDs of the neighboring nodes
    var left = nodeID - 1;
    var right = nodeID + 1;
    var up = nodeID - 10;
    var down = nodeID + 10;

    // Check if neighboring nodes exist and add them to the array of neighbors
    if (left >= 1 && left % 10 !== 0) {
        neighbors.push(document.getElementById('node' + left));
    }
    if (right <= 100 && right % 10 !== 1) {
        neighbors.push(document.getElementById('node' + right));
    }
    if (up >= 1) {
        neighbors.push(document.getElementById('node' + up));
    }
    if (down <= 100) {
        neighbors.push(document.getElementById('node' + down));
    }

    return neighbors;
}

Unable to to run Vue Black Dashboard in development

I’m looking for help with installing and running this dashboard template from Vue.

Here is the link: https://www.creative-tim.com/product/vue-black-dashboard

here is the docs:
https://demos.creative-tim.com/vue-black-dashboard-pro/documentation/quick-start.html#/

What I’m doing is downloading the zipped file, unzipping to desktop. Opening the folder in vs code. running :

npm install

in the terminal, the dependencies install and then when I type

npm run serve

to run the development server I get this error

  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

I’m completely confused and just trying to get this template up and running

I tried running npm i as normal to install the dependencies but it seems to not be working

Next.js routing breaks after router push

I have this really frustrating problem with routing in Next.js. So basically I have this group creation system, where you fill out a form, and create a group with a simple http request to a backend. But when I try routing to the subpage /[groupId], with the new id of the group I just created, it changes the url as expected but simply stops ALL routing from rerendering the client, and kind of freezes the page. links, other router pushes, etc., that worked perfectly before the redirect, suddenly stops rerendering the page, but still changes the url and rerenderes the same page the router.push was requested from. This bug ONLY happens in production and works perfect in development. No erros in the console. No nothing.

What I’ve tried to solve this:

  • Checked all component keys that might’ve prevented a rerender
  • Used the pathname directly – router.push("/groups/ACTUAL GROUP ID")
  • Searched every corner of the internet for a solution

I’m unfortunately unable to share the codebase, but will happily share some bites if needed.

Any help of any kind would be greatly appreciated.

try {
    const onSubmit = () => {
    ...
    const res = await axios(...);

    if (res) {
        router.push({
            pathname: "/groups/[groupId]",
            query: {
                groupId: "NEW ID"
            },
        });
      }
    }
} catch (err) {
    ...
}

Determine if two given regular expressions are equivalent [duplicate]

Is there a way to programmatically compare two regular expressions in Javascript and determine if they produce identical matches?

const regex1 = /[0-9]+/;
const regex2 = /d+/;
const regex3 = /[A-Z]{2}/;
const regex4 = /[A-Z][A-Z]/;

isEquivalentRegExp(regex1, regex2); // true
isEquivalentRegExp(regex2, regex3); // false
isEquivalentRegExp(regex3, regex4); // true

I’ve tried using the source attribute and the toString() function to do that, but they don’t work because they return the regular expression itself as a string.

// Not valid
function isEquivalentRegExp(r1, r2) {
  return r1.toString() == r2.toString();
}
// Not valid
function isEquivalentRegExp(r1, r2) {
  return r1.source  == r2.source;
}

How to aggregate objects in mongodb in same collection using _id

For eg my collection has data:

const categories=[
      {
        name:"1",
        _id:"100",
        parentCategory:null
      },
      {
        name:"2",
        _id:"101",
        parentCategory:'100'
      },
      {
        name:"3",
        _id:"103",
        parentCategory:'101'
      },
      {
        name:"4",
        _id:"104",
        parentCategory:'100'
      }
 ]

I want result data to be aggregated with subcategories inserted into array for 6-7 levels

Sample result needed:

[{name:'1',
  _id:'100',
  subCategories:[
    {
       name:'2',
       _id:'101',
       subCategories:[{
                 name:'3',
                 _id:'103'
                }
    },
    {
      name:'4',
      _id:'104'
   }
}
]

How can this be achieved using mongodb lookup funnction or any other function

How to fix Type ‘() => Promise’ is not assignable to type ‘number[]’ problem?

I thought using async/await allows to get value from the Promise, but it looks like I’m still getting a Promise.
So const ids gets an error Type ‘() => Promise<void | number[]>’ is not assignable to type ‘number[]’.
I just don’t understand hot to get number[] if async await son’t help. I’ll be very grateful for explanation.

I first need to get ids, set them to newsIds, and then send requests with every id I got, and set the data to latestNews.

export function NewsCardList() {
  const [newsIds, setNewsIds] = useState<number[]>();
  const [latestNews, setLatestNews] = useState<NewsItem[]>();

  useEffect(() => {
    const ids: number[] = async () =>
      await fetch(`url`)
        .then((res) => res.json())
        .then((data: number[]) =>
          data.filter((id: number, i: number) => i < 100)
        )
        .catch((e) => console.log(e));
    setNewsIds(ids);

    let urls = newsIds?.map(
      (id) => `url/item/${id}.json`
    );
    let requests = urls!.map((url) => fetch(url));

    Promise.all(requests).then((responses) =>
      Promise.all(responses.map((r) => r.json())).then((news) =>
        setLatestNews(news)
      )
    );
  }, []);

How do I break for loop in cypress when a specific value shows up on screen?

Here it’s going to the new page by clicking the next button again and again. One of the page has text ‘abc’ that I’m trying to find.

for(let n = 0; n < 150; n ++) {

    cy.get('.Next-Button').click();
    // some test code..

    cy.get('.selector').then($body => {
        if ($body.find('abc').length > 0) {
            return false; //used this to break the loop
        }
    });
}

The logic behind below code might not be clear but I basically want it to get out of loop when some value say ‘abc’ shows up on screen and continue with the code outside the for loop. But here it just keeps running the loop even after the value is found.

Using microsoft sharepoint with patternfly-timeline

I want to use patternfly-timeline chart in my sharepoint project.
To load the chart in my code, I tried

import "jquery";
import "bootstrap-selectpicker";
import "bootstrap-datepicker";
import "d3";

require("jquery");
require("timeline");
require("data");
require("script");

....

 public render(): void {
    this.domElement.innerHTML = `
    ....
    <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.11.0/js/bootstrap-select.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.min.js"></script>
    <script src="JS/timeline.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/patternfly/3.9.0/js/patternfly.min.js"></script>

    <script src="JS/data.js"></script>
    <script src="JS/script.js"></script>

To get external js files, in config.json, I set external libraries like

"externals": {
    "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
    "bootstrap": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js",
    "bootstrap-selectpicker": "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.11.0/js/bootstrap-select.min.js",
    "bootstrap-datepicker": "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js",
    "d3": "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js",
    "timeline": {
      "path": "./src/webparts/helloWorld/JS/timeline.js",
      "globalName": "timeline"
    },
    "data": {
      "path": "./src/webparts/helloWorld/JS/csvjson.js",
      "globalName": "data"
    },
    "script": {
      "path": "./src/webparts/helloWorld/JS/data.js",
      "globalName": "script"
    }
  },

Now, current problem is that this code cannot read jQuery, so error message is

script.js:3 
        
       Uncaught ReferenceError: $ is not defined
    at script.js:3:1

I followed some documentations to set ordering jQuery and my custom js files, but nothing has worked for me.

What is wrong with my code and what I have missed?

Sort Array Of Objects by different keys

I have an Array of Objects. I have displayed this Array of Objects using a for loop. This for loop has been created inside of a function.

let myArray = [
    {objectName: "Object 1"},
    {objectName: "Object 2"},
    {objectName: "Object 3"},
    {objectName: "Object 4"},
    {objectName: "Object 5"},
];
function displayMyArray(arrayName) {
    for (let i of arrayName) {
        let card = document.createElement("div");
        card.classList.add("card", i.category, "hide");
        let name = document.createElement("h5");
        name.classList.add("objectName");
        name.innerText = i.objectName.toUpperCase();
        container.appendChild(name);
        card.appendChild(container);
        document.getElementById("divToDisplayObjects").appendChild(card);
    }
}
displayMyArray(myArray);

This code works as expected.

I have created a Select Tag in HTML which contains multiple options. If the user clicks one of these options, the objects should be sorted in a paticular way. I have done this using the following code:

function sort() {
    let sortByValue = document.getElementById('sort-btn').value; // Get the value of the selected option
    let nameAscending = myArray.sort(// Code to sort the elements);
    if (sortByValue = "name_ascending") {
        document.getElementById("div_to_show_objects").innerHTML = "";
        displayMyArray(nameAscending);
    }
}
let sortByButton = document.getElementById("sort_btn");
sortByButton.addEventListner('change', sort());

If I click one of the options in the Select element of my HTML page, the ‘div_to_show_objects’ clears correctly, which means the correct function was called. However, the new sorted Array is not shown.

Why is this and how could I correct it?

I have looked at multiple different questions on Stack Overflow and have been unable to find an answer. I have also looked at multiple different videos and articles and have been unable to find an answer.

I have also tried adding a return statement to the end of the if statement. However this has not worked:

return displayMyArray(nameAscending);

When I log the value of ‘sortByValue’ to the console, it returns the correct result. However, the objects do not change order.

R Shiny – modular – dynamic inputs in datatable – editable data table – issues with binding & displaying

Reproducible Example

library(shiny)

apply_selectInput <- function(X) {
  paste0("selectInput(
    inputId = session$ns(",paste0("'type_input_",X[["row_name"]],"'"),"),
    label = NULL,
    choices = c('Other','Sports Car','Family Car'),
    selectize = FALSE
  )")
}

get_data <- function() {
  ## in mine, this is pulling in SQL data ##
  data <- as.data.frame(mtcars) %>%
    mutate(`Car Name` = rownames(mtcars))
  return(data)
}

get_data_w_inputs <- function(data = get_data()) {
  data$Type <- apply(
    X = data %>% mutate(row_name = rownames(data)),
    MARGIN = 1,
    FUN = apply_selectInput
  )
  return(data)
}

ui_function <- function(id) {
  ns <- NS(id)
  tagList(
    dataTableOutput(outputId = ns('dt')),
    uiOutput(outputId = ns('ui'))
  )
}

server_function <- function(input,output,session) {
  ns <- session$ns
  
  session$userData$vars <- reactiveValues(
    orig = get_data_w_inputs(),
    filtered = get_data_w_inputs(),
    changes = get_data_w_inputs(),
    inputs = NULL
  )
  
  output$dt <- renderDataTable({
    datatable(
      session$userData$vars$filtered %>% 
        mutate(Type = as.character(eval(parse(text = Type)))),
      rownames = FALSE,
      escape = FALSE,
      editable = list(target = "cell"),
      fillContainer = T,
      extensions = c('Buttons'),
      options = list(
        searching = FALSE,
        paging = FALSE,
        dom = 'tB',
        scrollY = '500px',
        scrollCollapse = TRUE,
        fixedColumns = TRUE,
        autoWidth = TRUE,
        buttons = c('copy', 'csv', 'excel'),
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
      )
    )
  })
  
  output$ui <- renderUI({
    print(input)
  })
}

## dashboard UI ##
ui <- dashboardPage(
  header = dashboardHeader(
    title = 'Test',
    controlbarIcon = shiny::icon("filter")
  ),
  sidebar = dashboardSidebar(
    
  ),
  controlbar = dashboardControlbar(
    
  ),
  body = dashboardBody(
    ui_function('datatable')
  )
)

## dashboard server ##
server <- function(input, output, session) {
  
  ## pull in modules ##
  callModule(server_function,'datatable')
  
}

shinyApp(ui,server)

Problem 1
One issue is that when I add the binding callbacks to the datatable, the entire thing disappears; however, if you dig into the back-end/inspect, all the rows are still there, it’s just that the height is set to 0. I can create a CSS file/edit this manually, but I don’t understand why it’s doing this and wondering if there’s a better way to keep this from happening in the first place.

Problem 2
The second issue is that the inputs are not actually binding to the namespace. I’ve tried seven thousand things after digging through Stack Overflow and NOTHING. WORKS. The closest I got was that the last row of the datatable’s input was binding, but not all at the same time. I’ve seen that most folks use a variety of apply when binding inputs from a dataframe, but when I do this, I get an error message saying it can’t find the session. I think this is because I have the functions separate from the module. However, I need this – I actually make calls to these functions in several spots (getting the data initially to set up filters, saving the data & refreshing it) and I don’t want to have to re-write this code every stinkin’ time.

I’ve been told to look into the DTedit package; however, I see that’s not a CRAN package and so I’d have to figure out how to tell my dockerfile to install it. It also pulls up an entire editing form instead of editing in-table (correct?) which I do not want.

Session Info

R version 4.2.1 (2022-06-23)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.4 LTS

other attached packages:
[1] DT_0.9

MUI-X DataGrid issues with singleSelect

I am having some issues with the singleSelect type on the community version of x-data-grid. My issue happens when I go to edit the row. My singleSelect is a list of data as follows.

Here is how my DataGrid is created. I know the editMode row is unnecessary at this time since there is only one column, but eventually I would like to use the row edit mode.

<DataGrid editMode="row" slots={{ toolbar: GridToolbar }} checkboxSelection={dataGridCheckboxes} rows={gridData || []} columns={columnsSetup} />

Here is how I setup the column. I only have 1 column at this time. The data pulls from a websocket between the react client and a websocket server to “simulate” pulling data from a database.

const columnsSetup = [
    {
        field: "test",
        headerName: "Object Dropdown",
        editable: true,
        type: "singleSelect",
        defaultValue: { short: "T2", numerical: 1 },
        valueOptions: [
            { short: "T2", numerical: 1 },
            { short: "T3", numerical: 2 },
            { short: "T4", numerical: 3 },
            { short: "T5", numerical: 4 },
            { short: "T6", numerical: 5 },
            { short: "T7", numerical: 6 },
            { short: "T8", numerical: 7 },
        ],
        valueFormatter: ({ value }) => {
            return value.short;
        },
        getOptionValue: (value) => value.numerical,
        getOptionLabel: (value) => value.short, // To populate the singleSelect dropdown list.
        sortComparator: (v1, v2) => {
            return gridNumberComparator(v1.numerical, v2.numerical);
        }
    },
];

Here is an example of how the data gets sent from the websocket.

[
    {
        "test": {
            "short": "T2",
            "numerical": 1
        },
    },
    {
        "test": {
            "short": "T5",
            "numerical": 4
        },
    },
]

Now, the numerical part of the object is for sorting purposes. Each “short” will be a different name and won’t have numbers in the coming future, so I figured the numerical part was the only way to be able to sort it the way I wanted.

When loaded into the grid, everything shows up properly. The issue I get is when I double click to edit, I am getting an error in the JS console and the select goes blank. I can still update the value, but do not want the select to go blank right as the edit starts.

This is the error I am receiving in the console.

You have provided an out-of-range value `[object Object]` for the select component.
Consider providing a value that matches one of the available options or ''.
The available values are `1`, `2`, `3`, `4`, `5`, `6`, `7`.

In edit mode, the values still show up in the dropdown, but it goes blank as mentioned. It seems to be an issue only for the object in a singleSelect. Strings work just fine!

Any help would be greatly appreciated!

how to add data-prices with several conditions

hello I have a code with +- 400 articles in these articles I added for some a data-category either aaa , or bbb , or ccc
these data-categories are contained in a tag a
Then for each article I have an input tag where there is a
data-name=”Option 1″
and a data-price=””
this data-price is variable

from there I would like to know the number of articles whose data-prix=”” is not empty for the data-categorie aaa , for the data-categorie “bbb” and for the data-categorie “ccc”
and then give me the sum of the data-prix for each data-categorie
I started with data-categorie “ccc” but it returns 0
what i would like
it is to make a loop which will look for me in the class “row mt-12” the child with the button to check and check if it is indeed data-categorie “ccc” if yes look in the second child if if data-nom is indeed equal to Option 1 if these conditions are respected you add data-prix; then make a loop which will execute this condition in an entire page

<script> var totalPrix = 0;
$('.row.mt-12').each(function() {
  if ($(this).find('a[data-categorie="ccc"] + div input[data-nom="Option 1"]').length) {
    totalPrix += parseFloat($(this).find('a[data-categorie="ccc"]').data('prix'));
  }
});
console.log(totalPrix);</script> 
     <div class="row mt-4">
                           <div class="form-check">
                             <input class="form-check-input 2017" type="checkbox" data-nom="Option 1" data-prix="-0.50" id="case_01" checked>                          
                           </div>
                         </div>
                       </div>
                            <div class="row mt-12">
                       
                           
                                              <div class="col-md-6 " style="margin-top: 5px;">
                                                <a style="cursor:pointer;" data-nom="2018"  data-checkbox="2018" data-categorie="ccc"  class="btn btn-primary ajouter-panier b-items__item__add-to-cart">
                                                    <div id="ajoute_encore_plus2018">Ajouter 1 sachet</div></a>
                                              </div>
                                           
                         <div class="row mt-4">
                           <div class="form-check">
                             <input class="form-check-input 2018" type="checkbox" data-nom="Option 1" data-prix="50" id="case_01" checked>                          
                           </div>
                         </div>
                       </div>

How can I get the source code of a variable in javascript?

I’m coding in Javascript and I’m trying to get the source code of the variable client.accountsBalanceGet. This variable allows me to view data from a fake bank account that is running within an API that I’m using. I want to see what the code behind that variable is.

My code so far is:

app.get('/api/balance', function (request, response, next) {
  Promise.resolve()
    .then(async function () {
      const balanceResponse = await client.accountsBalanceGet({
        access_token: ACCESS_TOKEN,
      });
      prettyPrintResponse(balanceResponse);
      response.json(balanceResponse.data);
    })
    .catch(next);

    
    

});

I want to get the source code of client.accountsBalanceGet and use what’s inside the source code in order to code another statement.