How to group a json object based on the equal key values using JavaScript

I have the following json object in javascript:

employeeRecords = [
    {
    "empID" : "7002",
    "company" : "Google",
    "group" : "Chrome",
    "id" : "D-2005",
    "city" : "New York",
    "date" : "2018-05-01"
    },
    {
    "empID" : "9002",
    "company" : "Apple",
    "group" : "iPhone",
    "id" : "D-2014",
    "city" : "Singapore"
    "date": "2019-07-15"
    },
    {
    "empID" : "7002",
    "company" : "Google",
    "group" : "Android",
    "id" : "H-2007",
    "city" : "London"
    "date": "2018-05-01"
    },
    {
    "empID" : "7002"
    "company" : "Google",
    "group" : "Android",
    "id" : "K-2007",
    "city" : "London"
    "date": "2019-06-18"
    },
    {
    "empID" : "9002",
    "company" : "Apple",
    "group" : "Laptop",
    "id" : "N-2012",
    "city" : "Japan"
    "date": "2019-07-15"
    }
]

The requirement is to group this json object, if the empID, company and the date is equal. If those key values are equal then the group field should be concatenated. I need to get this using JavaScript.

So the result should be like the following:

employeeRecords = [
    {
    "empID" : "7002",
    "company" : "Google",
    "group" : "Chrome-Android",
    "id" : "D-2005",
    "city" : "New York",
    "date" : "2018-05-01"
    },
    {
    "empID" : "9002",
    "company" : "Apple",
    "group" : "iPhone-Laptop",
    "id" : "D-2014",
    "city" : "Singapore"
    "date": "2019-07-15"
    },
    {
    "empID" : "7002"
    "company" : "Google",
    "group" : "Android",
    "id" : "K-2007",
    "city" : "London"
    "date": "2019-06-18"
    }
]

Any help to achieve this in JavaScript please?
Thanks in advance.

How does one call a js function after page has been closed?

I have a repeating js function that runs every [x] seconds. It works great as long as the page is open but is there a way to have it keep running even after the page has been closed?

This function is also part of a chrome extension I’m building, I’m guessing this might be possible with the MV3 service worker but if that’s the case I’m unsure on how I would go about doing that?

Any help is appreciated, thank you in advance!

Increment FieldValue in Firebase Web Modular 9?

I am trying to increment the value of rightVotes and wrongVotes. I am using updateDoc and increment to achieve it. I am having issue where it is replacing the whole stores array.

Here is my db snippet

Below is my code snippet. Any feedback on how can I just increment the specific FieldValue. I was able to achieve it with the node.js with earlier firebase version firebase.firestore.FieldValue.increment(1) but having issues with Firebase 9 Web Modular.

export const rightVote = async (productId, key) => {
  const productRef = doc(db, "products", productId);
  const updateKey = `stores.${[key]}.rightVotes`;
  await updateDoc(
    productRef,
    {
      [updateKey]: increment(1),
    },
    { merge: true }
  );
};

what the above code is doing is replacing the stores array.

Why doesn’t my regExp test code work on JS? [duplicate]

This is the regExp code that I wrote for phone number validation.
I’d like to get input formatted ‘(XXX)XXX-XXXX’. When I tested this on regexr.com, it worked. But It doesn’t work on my JS file.. Can you pls tell me What the problem is and how I can fix it?

const phoneReg = new RegExp('([0-9]{3})[0-9]{3}-[0-9]{4}')
console.log(phoneReg.test('(111)111-1111')) // false

Vue3 / Ionic: Auto Scroll down

I am writing a VueJS App with Ionic. The App also has a Chat. Obviously, you want to see the lastest message, not the oldest one, so the app needs to open with the container scrolled to the bottom (also, every time you get a new message, you want it to appear at the bottom).

My HTML-Template (parts):

  <ion-content
      :scroll-events="true">

    <ion-grid>
      <ion-row v-for="(message, index) in messages" v-bind:key="index"
               :id="(index === messages.length-1)? 'bottomMessage': 'notLastMessage'">
        <ion-col
            size="9"
            :offset="message.fromUsrName === user.name ? 3 : 0 "
            :class="
            message.fromUsrName === user.name
              ? 'my-message'
              : 'other-message'
          "
        >
          <b>{{ message.fromUsrName }}</b
          ><br/>
          <span>{{ message.text }}</span>
          <div class="time">
            {{ new Date(message.timestamp).toLocaleString() }}
          </div>
        </ion-col>
      </ion-row>
    </ion-grid>
  </ion-content>

I tried the following:

const element = document.querySelector('ion-grid')
element.scrollTop = element.scrollHeight;
document.querySelector('ion-content').scrollToBottom(0);
const messageDiv = document.getElementById('bottomMessage')
if (messageDiv) {
  messageDiv.scrollIntoView({behavior: "smooth"});
} else {
  console.log("no messageDiv");
}

and the suggested answer here:
Scroll to bottom of div?

None of that works, it refuses to scroll at all.
I also don’t get any error message, I also verified, that the document.querySelector (and the document.getElementById) actually find the element.

Since my data comes asynchronously, I also tried working with a timeout of 2 sec, to ensure that the data was loaded.

I would be grateful, if anyone has an idea on what I am missing or another great way of implementing my use case.

(I am starting to question my intelligence, this is a quit common use case, ain’t it?)

How to securely retrieve clients public key from popular wallet extensions

I am creating a desktop application which requires the user to connect their crypto wallet to “sign in”.

Here is my current workflow:

  1. Create a socket connection from desktop application to my server.
  2. Open a browser tab on the client machine that to page on my website, with the socket ID as a url parameter
  3. The page will prompt the user to connect their wallet
  4. After the connection was successful, the frontend makes an API call to the backend with the wallet address and the socket ID.
  5. The backend signs the wallet address with a private key and sends the address and the signature to the client’s desktop application using sockets.

The problem with this is that anyone could create a socket connection to my server and then make the request made in step 4 with whatever wallet address they want and the socket ID of the connection they made. Successfully being able to impersonate someone else’s wallet.

Any solutions to securely connect a the desktop app with the crypto wallet using a browser wallet extension?

The solution I am thinking about and would definitely work (if possible) is:

Use a publicly known string and encrypted it with the users private key and send this is a part of the request made in step 4. Then, the backend could just decrypt the data with the public address of the wallet and make sure it is equal to the original string. This way it can be verified that the public wallet address sent to the server is in fact owned by the user.

However, I do not think it is possible to be able to have the wallet extension encrypt data using the private key of the wallet. If there is a way that is compatible with the famous wallet extensions that would the perfect fix.

How can i prevent useEffect() from firing up the first time but listening for a state change?

I’m using react, node express, postgres

I have a react component that is an html table that gets populated from a postgres table.

Here is parent component Materials:

const Materials = () => {
    const [thickness1, setThickness] = useState(0);
    const [width1, setWidth] = useState(0);
    const [length1, setLength] = useState(0);
    const [partTotalDemand, setTotalDemand] = useState(0);
    const [partPlanned, setPlanned] = useState(0);
...

Here is a method in the component that retrieves data

// Material requirements calculation
    const getReq = async (id) => {
        try {
            const response = await fetch(`http://localhost:5000/materials/${id}`, [id])
            const jsonData = await response.json();

            const tempThickness = jsonData.parts_material_thickness
            const tempWidth = jsonData.parts_material_width
            const tempLength = jsonData.parts_material_length
            const tempTotalDemand = jsonData.workorder_total
            const tempPlanned = jsonData.parts_produced

            stateSetter(tempThickness, tempWidth, tempLength)
        } catch (err) {
            console.log(err.message);
        }
    }

I then want to update the states of the global constants:

const stateSetter = (thickness, width, length) => {
        try {
            setThickness(thickness);
            setWidth(width);
            setLength(length);

            console.log(thickness1);
            console.log(width1);
            console.log(length1);

        } catch (err) {
            console.log(err.message)
        }
    }

    useEffect(() => {
        stateSetter();
    }, [thickness1]);

Essentially the getReq() method is supposed to retrieve the information, and then I need to update the states with those values. As I understand I then need to re-render the component so the new states are usable. I attempted to do this via useEffect() but I’m not successful. The idea was to stop getReq() from firing up on the first render, but if the state changes for thickness1/width1/length1 then it should fire up and re-render, help much appreciated!

why is three.js not rendering this spinning cube? I believe i have everything correct but sometimes it helps to have a second set of eyes

I am not getting any errors which is confusing me, it renders a black screen. and because the HTML and CSS snippets are so tiny I believe my fault is hidden somewhere within the JS.

I really haven’t worked with three.js much so please don’t be too harsh with your criticisms, I know its probably a simple fix but sometimes my brain just doesn’t work correctly.

Thanks in advance! 😀

// The three.js scene: the 3D world where you put objects
const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  1,
  10000
);



const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xaaaaaa, 1);

document.body.appendChild(renderer.domElement);


const cube = {
  geometry: new THREE.BoxGeometry(1, 1, 1),
  material: new THREE.MeshBasicMaterial({ color: 0x00ff00 })
};

cube.mesh = new THREE.Mesh(cube.geometry, cube.material);

scene.add(cube.mesh);

camera.position.z = 5;

function render() {
  renderer.render(scene, camera);

 
   cube.mesh.rotation.x += 0.08;
  cube.mesh.rotation.y -= 0.05;
  
  requestAnimationFrame(render);
}
html, body {
    overflow: hidden;
    user-select: none;
  padding: 0;
  margin: 0;
}

canvas {
    width: 100%; 
    height: 100%;
    padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    
    <title>Three.js app</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js"></script>
    <script src="script.js"></script>
  </body>
</html>

How to get darker shadow when a character inside another object’s shadow in ThreeJS?

In my scene, I’m using AmbientLight and DirectionalLight. As you can see in the images, there are trees and a character. Trees have big shadows, also my character casts shadow as well. The thing I want is, when my character inside the shadow of a tree, it casts darker shadow of itself to the ground. For the ground, I’m using PlaneGeometry and MeshStandardMaterial.

enter image description here

I need characters shadow (darker) in here as well;

enter image description here

I need something like this:

enter image description here

Scroll Bar Hiding and Unhiding on pages load

I Tried to find some topic about this issue but i haven’t found..

I have a problem on my website, when loading my pages, the scroll bar get hide and unhide just for 1 second that causes content to shift fast..

Yes, i already have tried this code, and i’m using it now:

html {
    overflow-y: scroll;
}

However the problem still there. This problem occours on the latest version of google chrome.

I have a live example if someone want to see, just switch to home -> episodios page:
Live site

I apretiate your help!

I have this error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

i have this error and i need help please

this is my code

 <script type="text/javascript">
    
    function ajax_send(data,element){
                
        var ajax = new XMLHttpRequest();
        
        
        ajax.addEventListener('readystatechange', function(){
                              
             if(ajax.readyState == 4 && ajax.status == 200){
            
                response(ajax.responseText,element);
             }                 
        });
        
        data = JSON.stringify(data);
        
        ajax.open("post","<?=ROOT?>ajax.php",true);
        ajax.send(data);
    }
    //console.log(result);
    function response(result,element){
     
        if(result != ""){
            
            
            var obj = JSON.parse(result);
            //element.innerHTML = obj.likes;
            
            if(typeof obj.action != 'undefined'){
                
                if(obj.action == 'like_post'){
                    
                    var likes = "";
        
                    if(typeof obj.likes != 'undefined'){
                        likes = (parseInt(obj.likes) > 0) ? "Like(" +obj.likes+ ")" : "Like" ;
                        element.innerHTML = likes;
                    }
                    
                    if(typeof obj.info != 'undefined'){
                        var info_element = document.getElementById(obj.id);
                        info_element.innerHTML = obj.info;
                    }
                }
            }
        }
    }
    
    function like_post(e){
        
        e.preventDefault();
        var link = e.target.href;
        var data = {};
        data.link = link;
        data.action = "like_post";
        ajax_send(data,e.target);
    }
</script>

i cant figure out how to get this span to close both modals

I am trying to make multiple modals that show different stuff when opened but, only the first modal will close and the second modal won’t close when I press the span button. when console logged it only shows the first modals spans id it won’t show the second spans id. is their ant DRY way of fixing this.

HTML

<!--Work-->
            <div id="work">
                
                <h2>Work</h2>

                <ul>
                    <li>
                        <button class="nobs-modal-btn"><img src="./assets/images/favicon.oe.ico" alt="No Ordinary Burritos website" width="200px" height="200px"></button>
                        <p>No ordinary burritos</p>
                    </li>
                    <li>
                        <button class="run-buddy-modal-btn"><img src="./assets/images/hero-bg.jpg" alt="" width="200px" height="200px"></button>
                        <p>Run buddy</p>
                    </li>
                </ul>
            </div>
            <!-- end Work -->

            <!-- nobs Modal -->
            <div id="nobs-modal" class="modal">

                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close">&times;</span>
                    <p>Some text in the Modal..</p>
                </div>

            </div>

             <!-- run buddy Modal -->
             <div id="run-buddy-modal" class="modal">

                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close">&times;</span>
                    <img src="./assets/images/hero-bg.jpg" alt="">
                </div>

            </div>

js

// Get the modal
var nobsModal = document.querySelector("#nobs-modal");
const runBuddyModal = document.querySelector("#run-buddy-modal")

// Get the button that opens the modal
var nobsBtn = document.querySelector(".nobs-modal-btn");
const runBuddyBtn = document.querySelector(".run-buddy-modal-btn");

// Get the <span> element that closes the modal
var span = document.querySelector("span");

// display modal
nobsBtn.addEventListener('click', () => {
  nobsModal.style.display = "block"
})

runBuddyBtn.addEventListener('click', () => {
  runBuddyModal.style.display = 'block'
})

span.addEventListener('click', () => {
  nobsModal.style.display = "none"
  runBuddyModal.style.display = 'none'
})

// When the user clicks anywhere outside of the modal, close it
window.addEventListener('click', function(event) {
    if (event.target == runBuddyModal) {
      runBuddyModal.style.display = "none";
    }
})

window.addEventListener("click", function(event) {
    if (event.target == nobsModal) {
      nobsModal.style.display = "none";
    }
    console.log(event)
})

What I code do I add to change this bar chart in real-time in JavaScript?

I’m trying to automatically update this bar chart. I’ve looked on websites for what code to add, and I don’t know how to apply it to what I have.
Here is the page the bar chart is on: https://lifespringchurch.com/spiritual-gifts-survey/
(The bar chart is at the very bottom of the page.)
After a person is done with the survey, their final tallies should be shown in the bar graph.

<html>
<head>
<script src="https://cdn.anychart.com/releases/8.0.0/js/anychart-base.min.js"></script>
</head>
<body>
<div id="container" style="width: 75%; height: 75%"></div>
<script>
anychart.onDocumentReady(function() {

// set the data
var data = {
header: ["Gift", "Value"],
rows: [
["Leadership", document.getElementById("ninja_forms_field_464").value],
["Administration", document.getElementById("ninja_forms_field_465").value],
["Teaching", document.getElementById("ninja_forms_field_467").value],
["Knowledge", document.getElementById("ninja_forms_field_468").value],
["Wisdom", document.getElementById("ninja_forms_field_469").value],
["Prophecy", document.getElementById("ninja_forms_field_470").value],
["Discernment", document.getElementById("ninja_forms_field_471").value],
["Exhortation", document.getElementById("ninja_forms_field_472").value],
["Shepherding", document.getElementById("ninja_forms_field_473").value],
["Faith", document.getElementById("ninja_forms_field_474").value],
["Evangelism", document.getElementById("ninja_forms_field_475").value],
["Apostleship", document.getElementById("ninja_forms_field_476").value],
["Service", document.getElementById("ninja_forms_field_477").value],
["Mercy", document.getElementById("ninja_forms_field_478").value],
["Giving", document.getElementById("ninja_forms_field_479").value],
["Hospitality", document.getElementById("ninja_forms_field_480").value]
]};


// create the chart
var chart = anychart.column();


// add the data
chart.data(data);

// draw
chart.container("giftgraph");
chart.draw();

});
</script>
</body>
</html>