how to select any href using JavaScript?

The following code is used for my sidebar to be able to set the active subpage and properly display the the sidebar when refreshing the page.

It works well if I add the “#” symbol to the href of the subpages but didn’t work when changing the href to anything else and removing the “#” symbol. Let’s suppose I want to set the href as “/contactpage/. How do I indicate in the below code to choose any href not only the ones that contains the hash symbol?

  <script>

      (() => {
        'use strict'
      
      
      
        function setActiveItem() {
          const { hash } = window.location
      
          if (hash === '') {
            return
          }
      
          const link = document.querySelector(`.d-flex a[href="${hash}"]`)
      
          if (!link) {
            return
          }
      
          const active = document.querySelector('.d-flex .active')
          const parent = link.parentNode.parentNode.previousElementSibling
      
          link.classList.add('active')
      
          if (parent.classList.contains('collapsed')) {
            parent.click()
          }
      
          if (!active) {
            return
          }
      
          const expanded = active.parentNode.parentNode.previousElementSibling
      
          active.classList.remove('active')
      
          if (expanded && parent !== expanded) {
            expanded.click()
          }
        }
      
        setActiveItem()
        window.addEventListener('hashchange', setActiveItem)
      })()
      
      
      
      </script> 

How to compare two objects using JavaScript language and return a number between 0 and 100 representing the percentage of similarity as the result

I followed this tutorial (https://www.tutorialspoint.com/compare-two-objects-in-javascript-and-return-a-number-between-0-and-100-representing-the-percentage-of-similarity) to be able to compare two objects in JavaScript and return a number between 0 and 100 representing the percentage of similarity.

However, that only works for exact key-value pairs in both objects. I also need to be able to compare number intervals (like on the third “if” statement below for example). The expected result is 70, but currently I am getting 80 (if you comment all “if” statements after the second one, it will give you 40 as the result, which is Correct).

My problem starts when I write the third “if” statement and continue with the others. Actually, after the 3rd “if” statement, the other “if’s” don’t make any difference on the final result (I don’t know why). Could somebody help to find a suitable solution, please?

const a = {
  especie: 'cachorro',
  idade_min: 1,
  idade_max: 3,
  sexo: 'M',
  peso_min: 5,
  peso_max: 10,
  tamanho: 50,
  porte: 100,
  cor: 'preta',
  raça: 'pitbull',
  castrado: true,
  vacinado: true,
};

const b = {
  especie: 'cachorro',
  idade: 2,
  sexo: 'M',
  peso: 10,
  tamanho: 25,
  porte: 100,
  cor: 'branca',
  raça: 'pitbull',
  castrado: false,
  vacinado: false,
};

const findMatch = (first, second) => {
  const firstLength = Object.keys(first).length;
  const secondLength = Object.keys(second).length;
  const smaller = firstLength < secondLength ? first : second;
  const greater = smaller === first ? second : first;

  const count = Object.keys(smaller).reduce((acc, key) => {
    let counter = acc;

    if (Object.keys(greater).includes(key)) {
      if (greater[key] === smaller[key]) {
        console.log(counter);
        return ++counter;
      };

      if (b.idade <= a.idade_max && b.idade >= a.idade_min) {
        return ++counter;
      };

      if (b.peso <= a.peso_max && b.peso >= a.peso_min) {
        return ++counter;
      };

      if (b.tamanho <= a.tamanho) {
        return ++counter;
      };

      if (b.porte <= a.porte) {
        return ++counter;
      };
    };

    console.log(counter);
    return counter;
  }, 0);

  return (count / Math.min(firstLength, secondLength)) * 100;
};

console.log(findMatch(a, b)); // expected result = 70?

blocked by CORS policy but still POST request is performed, HOW?

I had a server running on localhost port 3000 using NodeJs.

There I had a database linked and had 2 basic POST methods (Create and Delete)*.

*(I had not written any extra checking for request headers)

I was curious to know if only client-side JS (with a dummy HTML page) can perform the deletion by itself!

I wrote THIS in the client-side js (in a separate directory )

After trying the POST Delete operation like this ,
I got this ERROR

But even though error was raised, the “Deletion Operation” was still performed succesfully and the data with the specific id was deleted!

My Question is “what exactly is blocked if it was not the deletion operation ?

how to get messages (data) in real time from database using ajax and django

i want to get messages in realtime using ajax and django for the backend, i have written the logic to send the messages and that is working, but i want to get a message immediately another user sends me a message without having to refresh the page, i tried using ajax interval but it seem i am not getting a hang of how to properly use the interval and forloop in ajax, what is it that i should do to achive the result i want?

directs.html

<div class="chat-wrapper">
    {% for direct in directs %} {% if direct.sender == request.user %}
    <div class="chat-message-right pb-2">
        <div>
            <a href=""><img src="{{ direct.sender.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40" /></a>
            <div class="text-muted small text-nowrap mt-2" style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div>
        </div>
        <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3">
            <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> -->
            {{direct.body}}
        </div>
    </div>
    {% else %}
    <div class="chat-message-left pb-2">
        <div>
            <a href=""><img src="{{ direct.sender.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40" /></a>
            <div class="text-muted small text-nowrap mt-2" style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div>
        </div>
        <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3">
            <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> -->
            {{direct.body}}
        </div>
    </div>
    {% endif %} {% endfor %}
</div>

<script>
    $(document).ready(function () {
        setInterval(function () {
            $.ajax({
                type: "GET",
                url: "",
                success: function (response) {
                    console.log("Sending");
                    for (var key in response.directs) {
                        let _html =
                            '<div class="chat-message-right pb-2">
                                <div>
                                    <a href=""><img src="{{ request.user.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40"></a>
                                    <div class="text-muted small text-nowrap mt-2" style="font-size:10px; color: rgba(180, 180, 180, 0);"><p style="font-size:10px; color: black;">{{direct.date|date:"d M, Y"}}</p></div>
                                </div>
                                <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3">
                                    <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> -->
                                    ' +response.directs[key].body +"
                                </div>
                            </div>
                            ";
                        $(".chat-wrapper").append(_html);
                    }
                },
            });
        }, 10000);
    });
</script>



<!-- Sending message function and ajax logic -->
<div class="flex-grow-0 py-3 px-4 border-top">
    <form id="chat-form">
        {% csrf_token %}
        <div class="input-group">
            <input type="hidden" name="to_user" id="to_user" value="{{active_direct}}" />
            <input name="body" id="body" type="text" class="form-control" placeholder="Type your message" required />
            <button class="btn btn-primary" type="submit">Send</button>
        </div>
    </form>

    <script type="text/javascript">
        $(document).on("submit", "#chat-form", function (e) {
            e.preventDefault();
            let _body = $("#body").val();
            let _to_user = $("#to_user").val();

            $.ajax({
                type: "POST",
                url: "{% url 'send-directs' %}",
                data: {
                    body: _body,
                    to_user: _to_user,
                    csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
                },
                success: function (data) {
                    console.log("working");
                    let _html =
                        '<div class="chat-message-right pb-2">
                            <div>
                                <a href=""><img src="{{ request.user.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40"></a>
                                <div class="text-muted small text-nowrap mt-2" style="font-size:10px; color: rgba(180, 180, 180, 0);"><p style="font-size:10px; color: black;">{{direct.date|date:"d M, Y"}}</p></div>

                            </div>
                            <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3">
                                <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> -->
                                ' +_body +"
                            </div>
                        </div>
                        ";
                    $(".chat-wrapper").append(_html);
                },
            });
            document.getElementById("body").value = "";
        });
    </script>
</div>

views.py


@login_required
def Directs(request, username):
    user  = request.user
    messages = Message.get_message(user=user)
    active_direct = username
    directs = Message.objects.filter(user=user, reciepient__username=username)  
    directs.update(is_read=True)

    for message in messages:
            if message['user'].username == username:
                message['unread'] = 0
    context = {
        'directs': directs,
        'messages': messages,
        'active_direct': active_direct,
    }
    return render(request, 'directs/direct.html', context)

def SendDirect(request):
    

    if request.method == "POST":
        from_user = request.user
        to_user_username = request.POST['to_user']
        body = request.POST['body']

        to_user = User.objects.get(username=to_user_username)
        Message.sender_message(from_user, to_user, body)
        # return redirect('message')
        success = "Message Sent."
        return HttpResponse(success)

document is not defined in ReactJS chrome extension

I’m currently building a chrome extension using React.js. I need to run a script to get the input element of the active tab, so in my background/index.js file I tried to do a document.getElementsByTagName("input") but I received:

Uncaught ReferenceError: document is not defined

I don’t use ReactDOM because it’s not a file to render so I don’t know how to access to the document.

Help would be appreciated !

I am trying to save the values form the DataGridPro MUI, a TreeData … How can i save Values of the Cells after i edit them

I am novice at this. I am trying to save the values form the DataGridPro MUI, I am using a TreeData. How can i save Values of the Cells after i edit them. I watched a video online in by which i was able to understand how it will work on a Single DataTable, But for the Parent one, i dont know how i will be able to save it. I have looked up but i found no method which could be helpful. I am getting the values from the GridColumn and GridRowsProp.

Basically i want to save the values of the children. apply CRUD on it for later use. How can I do that?
Thanks.

import * as React from "react";
    import { DataGridPro, GridColumns, GridRowsProp, DataGridProProps } from "@mui/x-data-grid- 
    pro";
    import {
    GridCellEditCommitParams,
    GridCellEditStopParams,
    GridCellEditStopReasons,
      GridRowModel,
  MuiEvent,
} from "@mui/x-data-grid";
import { applyInitialState } from "@mui/x-data-grid/hooks/features/columns/gridColumnsUtils";

const rows: GridRowsProp = [
  {
    hierarchy: ["Documents"],
    rubrics: "Head of Human Resources",
    totalMarks: "",
    id: 0,
  },
  {
    hierarchy: ["Scope"],
    rubrics: "Head of Sales",
    totalMarks: "15",
    id: 1,
  },
  {
    hierarchy: ["Scope", "Rubric item 1"],
    rubrics: "Sales Person",
    totalMarks: "2",
    id: 2,
  },
  {
    hierarchy: ["Scope", "Rubric item 2"],
    rubrics: "Sales Person",
    totalMarks: "5",
    id: 3,
  },
  {
    hierarchy: ["Scope", "Rubric item 3"],
    rubrics: "Sales Person",
    totalMarks: "8",
    id: 4,
  },
];

const columns: GridColumns = [
  { field: "rubrics", headerName: "Rubric Type", width: 200, editable: true },
  {
    field: "totalMarks",
    headerName: "Total Marks",

    width: 150,
    editable: true,
  },
];

const getTreeDataPath: DataGridProProps["getTreeDataPath"] = (row) => row.hierarchy;

export default function TreeDataSimple() {
  const [state, setState] = React.useState<GridRowModel[]>(applyInitialState); //i was seeing online for this how can i add the array here but no luck.
  const handleCommit = (e: GridCellEditCommitParams) => {
    const array = state.map((r) => {
      if (r.id === e.id) {
        return { ...r, [e.field]: e.value };
      } else {
        return { ...r };
      }
    });
    setState(array);
  };
  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGridPro
        treeData
        rows={rows}
        columns={columns}
        getTreeDataPath={getTreeDataPath}
        onCellEditCommit={handleCommit}
        experimentalFeatures={{ newEditingApi: true }}
        onCellEditStop={(params: GridCellEditStopParams, event: MuiEvent) => {
          if (params.reason === GridCellEditStopReasons.cellFocusOut) {
            event.defaultMuiPrevented = true;
          }
        }}
      />
    </div>
  );
}}

How to manage dependents async await in ReactJS? [duplicate]

I’m still new to ReactJS and I’m having trouble doing an asyn await with dependencies from another request on axios.

I need to get a list of pokemon, this list returns me the name of pokemons.

With this list of names, I need to make another request, where I will pass this name that I received as a parameter.

In addition to passing the name as a parameter, I need to make a call with axios.get() using .map(). Because there are several calls I need to make. It is possible?

However, I am not able to do that. Can you tell me what I’m doing wrong?

Here’s my code I put into codesandbox.io

import React from "react";
import axios from "axios";
import "./styles.css";

const App = () => {
  const BASE_URL = "https://pokeapi.co/api/v2";

  const getAllPokemons = async () => {
    const { data } = await axios.get(`${BASE_URL}/pokemon`);

    // Here is my pokemon list
    console.log(data);

    data.results.map((poke) => getPokeType(poke));
  };

  const getPokeType = async (poke) => {
    const { data } = await axios.get(`${BASE_URL}/type/${poke.name}`);

    console.log("data: ", data);
  };

  React.useEffect(() => {
    getAllPokemons();
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
};

export default App;

enter image description here

Thank you very much in advance.

Get Open Graph data on front end by JavaScript for static website?

Is it possible for a static website to fetch Open Graph data using plain/vanilla (no library dependencies) JavaScript on the front end (such as by XMLHttpRequest)?

For example, if a webpage were to have a list of URLs, could a script be written that upon page load would loop through the URLs, submit a request for the title, description, and other og: meta data found in each URL’s HTML content, and upon receipt of those data, then create or edit elements in the DOM to display them to the user?

All I’m finding online are libraries and packages designed for back-end usage with NPM or the like. Thank you.

Slick Slider showing 3 images i/o on mobile

Thanks in advance for any help!

I have a grid (table), I formatted it to be same size across devices at 940px wide with overflow-scroll for mobile devices so table can be viewed at full size by side scrolled.

I am using slick sliders to add arrow controls but have disabled all touch/swipe on it so it was only controlled by arrows. I have also set all controls to only show 1 slider at a time, however on mobile when side swiping I see all three.

Just fyi – I am using Webflow builder so I am only custom coding for slick slider.

Image of table -desktop view – all correct

Code inserted to disable:

swipeToSlide: false, 
arrows: false, 
draggable: false, 
touchMove: false, 
swipeToSlide: false, 
touchThreshold:0, 

On mobile the carousel shows all three slides, even settings are set to 1 and arrow controls slide only one.

slidesToShow: 1, 
slidesToScroll: 1, 

AND

responsive: [ 
{ 
// tablet 
breakpoint: 991, 
settings: { 
slidesToShow: 1 
} 
}, 
{ 
// mobile portrait
breakpoint: 479,
settings: {
slidesToShow: 1
}
}
]

mobile you can see more than one slide- separated by green side cells

I want to only view one slide on mobile with overflow side scroll grid so you can see full grid on side scroll but not all three slides.

Ready only: Webflow – Anastasia Stallcop Portfolio
https://preview.webflow.com/preview/anastasiastallcop-09463966869e63530c18a?utm_medium=preview_link&utm_source=designer&utm_content=anastasiastallcop-09463966869e63530c18a&preview=e4ad52b0551c0685b1b170f3fd29714d&pageId=62b67bbd0134354aa31af254&workflow=preview

Published:
https://anastasiastallcop-09463966869e63530c18a.webflow.io/case-study-template-copy-2

HEAD CODE

<style>

.text-contain  {pointer-events: none;}

.list::-webkit-scrollbar {
  display: none;
}

</style>

BODY CODE

<!-- NEW Dragable Slider -->
<style>
.item {display: inline-block;}
.list {display:block !important;}
.slick-prev:hover,
.slick-prev:focus,
.slick-next:hover,
.slick-next:focus
{
    outline: none;
}
.slick-slide, .slick-slide *{ outline: none !important; }
</style>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/slick/slick.min.js"></script>

<script>


// when document is fully loaded
$( document ).ready(function() {


$('.list').slick({
  dots: false,
  speed: 700,
  infinite: true,
  swipe: false,
  slidesToShow: 1,
  slidesToScroll: 1,
  swipeToSlide: false,
  arrows: false,
  draggable: false,
  touchMove: false,
  swipeToSlide: false,
  touchThreshold:0,
  responsive: [
    {
      // tablet
      breakpoint: 991,
      settings: {
        slidesToShow: 1
      }
    },
    {
      // mobile portrait
      breakpoint: 479,
      settings: {
        slidesToShow: 1
      }
    }
  ]
});

$('.slider-prev').click(function(){
    $("#slider-id").slick('slickPrev');
});

$('.slider-next').click(function(){
    $("#slider-id").slick('slickNext');
});


});


</script>

how to create an html table from an html form using javascript [closed]

I have created an html form and I would like that each time someone fills the form, an html table is created and filled with the information retrieved in the form, all in javascript if possible, although I am open to other possibilities.

I already tried to do it, but it doesn’t work, I put the code below:

Formulaire html:

<div id="party">
        <form action="">
        <h1>Publication</h1>
        <div>
        <label for="nom">Nom de la pool party :</label>
        <input type="text" id="nom" name="nom" placeholder="nom de la pool party" required> 
        </div>
        <div>
        <label for="adresse">Adresse de la pool party :</label>
        <input type="text" id="adresse" name="adresse" placeholder="adresse de la pool party" required>
        </div>
        <div>
        <label for="capacite">Capacité d'acceuil :</label>
        <input type="text" id="capacite" name="capacite" placeholder="capacité d'acceuil de la pool party" required>
        </div>
        <div> 
        <label for="phone">Numéro de téléphone (facultatif) :</label>
        <input type="text" id="phone" name="phone" placeholder="numéro de téléphone" required>
        </div>
        <div>  
        <label for="heure1">Heure de début :</label>
        <input type="text" id="heure1" name="heure1" placeholder="10h15" required>
        </div>
        <div>
        <label for="heure2">Heure de fin :</label>
        <input type="text" id="heure2" name="heure2" placeholder="20h15" required>
        </div>
        <button type="submit">Publier</button>
    </div>

Javascript code:

let btn = document.getElementById("nav");
let party = document.getElementById("party");
let ntable = 0;

btn.addEventListener("click", () => {
    btn.style.display = "none";
    party.style.display = "block"
});

let button = document.querySelector('button[type="submit"]');

button.addEventListener("click", () => {

    localStorage.setItem("nom", document.querySelector("#nom").value);
    localStorage.setItem("adresse", document.querySelector("#adresse").value);
    localStorage.setItem("capacite", document.querySelector("#capacite").value);
    localStorage.setItem("phone", document.querySelector("#phone").value);
    localStorage.setItem("heure1", document.querySelector("#heure1").value);
    localStorage.setItem("heure2", document.querySelector("#heure2").value);
    
    if (document.querySelector("#nom").value !== "" && document.querySelector("#adresse").value !== "" && document.querySelector("#capacite").value !== "" && document.querySelector("#phone").value !== "" && document.querySelector("#heure1").value !== "" && document.querySelector("#heure2").value !== "") {
 
        
        console.log("");
        ntable = 1;
}

});

if (ntable = 1) {
    localStorage.setItem("nom", document.querySelector("#nom").value);
    localStorage.setItem("adresse", document.querySelector("#adresse").value);
    localStorage.setItem("capacite", document.querySelector("#capacite").value);
    localStorage.setItem("phone", document.querySelector("#phone").value);
    localStorage.setItem("heure1", document.querySelector("#heure1").value);
    localStorage.setItem("heure2", document.querySelector("#heure2").value);
    
        let table = document.createElement('table');
        let td = document.querySelector('td');
        let tr = document.querySelector('tr');

        document.querySelector('body').appendChild(table);

        let row_1 = document.createElement('tr');
        let heading_1 = document.createElement('td');
        heading_1.innerHTML = "Nom de la pool party";
        let heading_2 = document.createElement('td');
        heading_2.innerHTML = "heure de début";
        let heading_3 = document.createElement('td');
        heading_3.innerHTML = "heure de fin";
        let heading_4 = document.createElement('td');
        heading_4.innerHTML = "adresse";
        let heading_5 = document.createElement('td');
        heading_5.innerHTML = "capacité";
        let heading_6 = document.createElement('td');
        heading_6.innerHTML = "téléphone";

        row_1.appendChild(heading_1);
        row_1.appendChild(heading_2);
        row_1.appendChild(heading_3);
        row_1.appendChild(heading_4);
        row_1.appendChild(heading_5);
        row_1.appendChild(heading_6);
        table.appendChild(row_1);


        let row_2 = document.createElement('tr');
        let row_2_data_1 = document.createElement('td');
        row_2_data_1.innerHTML = document.querySelector("#nom").value;
        let row_2_data_2 = document.createElement('td');
        row_2_data_2.innerHTML = document.querySelector("#heure1").value;
        let row_2_data_3 = document.createElement('td');
        row_2_data_3.innerHTML = document.querySelector("#heure2").value;
        let row_2_data_4 = document.createElement('td');
        row_2_data_4.innerHTML = document.querySelector("#adresse").value;
        let row_2_data_5 = document.createElement('td');
        row_2_data_5.innerHTML = document.querySelector("#capacite").value;
        let row_2_data_6 = document.createElement('td');
        row_2_data_6.innerHTML = document.querySelector("#phone").value;

        row_2.appendChild(row_2_data_1);
        row_2.appendChild(row_2_data_2);
        row_2.appendChild(row_2_data_3);
        row_2.appendChild(row_2_data_4);
        row_2.appendChild(row_2_data_5);
        row_2.appendChild(row_2_data_6);
        table.appendChild(row_2);

        table.style.background = "white";
        table.style.color = 'black';
        table.style.textAlign = "center";
        table.style.border = "1px solid black";
        td.style.border = "1px solid black";
        tr.style.border = "1px solid black";
        ntable = 0;
};

How do I get the Age data from child to parent component

Parent.js

import React, { useState } from 'react'
import Child from './Child'

const Parent = () => {
    const[data,setData] = useState('')
    const[name,setName] = useState('')
    const[toggled,setToggled] = useState(false)
    const[age,setAge] = useState('')

    const ageToChild = (ageData) =>{
        setAge(ageData)
    }
    const childToParent = (childData) =>{
        setData(childData)
    }

    const handleSubmit = (e) =>{
        e.preventDefault()
        alert(`Age is ${age} , Form Submitted`)
        console.log(`Name is ${name} and Age is ${age}`)
    }
  return (
    <>
        {data}
        <div>
            {/* <Child childToParent={childToParent}></Child> */}
            <form onSubmit={handleSubmit}>
                <label>Name : </label>
                <input type="text" value={name} onChange={(e)=>setName(e.target.value)}></input>
                <button type='button' onClick={()=>setToggled(!toggled)}>Age ?</button>
                {toggled && <Child childToParent={childToParent} ageToChild={ageToChild}></Child>}
                <button type='button'>Submit</button>
            </form>
        </div>
    </>
  )
}

export default Parent

Child.js

import React from 'react'

const Child = ({childToParent,ageToChild}) => {
    const data = "This is some data from the child component to parent"
    // const age = ageToChild
  return (
    <>
        <button onClick={()=>childToParent(data)}>Click Child</button>
        <label>Age : </label>
        <input type='text' onChange={()=>ageToChild()}></input>
    </>
  )
}

export default Child

I am getting output as Name is inputtedname and Age is Undefined , How do I get the user inputted age value logged in the console?
I am trying to pass data from child to parent using functional components

Converting a list of objects to a different list of objects in javascript [duplicate]

I’m having a problem that I’m having a hard time with. I have a list of exercises objects like below:

exerciseDataList = 

[
{exerciseType: 'Legs', activity: 'Squats', weight: '180', reps: '10'},
{exerciseType: 'Legs', activity: 'Squats', weight: '180', reps: '10'},
{exerciseType: 'Legs', activity: 'Leg Press', weight: '150', reps: '10'},
{exerciseType: 'Legs', activity: 'Leg Press', weight: '140', reps: '10'},
{exerciseType: 'Chest', activity: 'Bench Press', weight: '180', reps: '10'},
]

I’m hoping to turn the above to below:

treeData = 
[
  {
    'name':'Legs',
    'data': [{'x':'Squats','y':3600}, {'x':'Leg Press', 'y':2900}]
  },
  {
    'name':'Chest',
    'data': {'x': 'Bench Press', 'y': 1800}
  }
]

Essentially data.x is the activity and data.y is the sum of weight * reps for the same exerciseType and activity.

I’m having a hard time wrapping my head around this and wondering what would be the efficient way to do this as the exerciseDataList can get long.

I know I need to loop through the list of exercise objects and treeData but this is when I’m not sure what to do next. I feel like to achieve this I need 3 for loops? How would I go about doing this and is there a better solution that O(n^3)? Thank you.

for (let edata of this.getExerciseDataList) {
  for (let data of this.treeData) {
    .....
  }
}

Few lines of misunderstood Js code, what do they do? [Js] [duplicate]

can anyone tell me what these few lines of code do? The first 2 from what I understand return the first element that belongs to the class or classes in brackets … I did not understand then the following lines …

let menu = document.querySelector('#menu-btn');
let navbar = document.querySelector('.header .navbar');

menu.onclick = () =>{
menu.classList.toggle('fa-times');
navbar.classList.toggle('activee');
 };