I want to call a my secure Rest API created in Spring boot using Javascript but its giving error

I have created a secure Rest API in Spring boot which I want to send a POST fetch request to using java script. I have defined an InMemoryUser in my configuration class. The problem is that, everything works perfectly fine when I send a POST request using Postman. But when i send a POST request using Java script i get error.

This is how i tried to send the post request using the Java Script
document.querySelector(.btn_save_student)
.addEventListener(‘click’, async()=> {
let name = document.getElementById(name).value;
let email = document.getElementById(email).value;
let user_password = document.getElementById(user_password).value;

let username = 'user';
let password = '12345';
let auth = btoa(`${username}:${password}`);

try {
    let response = await fetch(`http://localhost:8081/api/v1/employee/save`, {
        method: 'POST',
        headers: {
            'Authorization': `Basic ${auth}`,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify ({
            'name':name,
            'email': email,
            'password': user_password
        })   
    })

    let data_res = await response.json();
    console.log(data_res);
} catch (error) {
    alert(error)
}

});

And I got this error:
Access to fetch at ‘http://localhost:8081/api/v1/employee/save’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Drag&Drop feature in jquery drops element at seemingly random position

I got some problem with my code but I simply cannot put my finger on what would be at fault in that situation I am lost.

So the situation is as follows, I am making a simple drag and drop interface by using jquery, all it does is: Make a grid, add/remove “pawns” depending on a certain table in the same page and drag&drop whatever pawn you want in whatever square you wish to. Everything works as expected but almost always when I try to drop the pawn on a square it teleports in a random position, rarely it does drop where it is expected to. I am not sure it is relevant but I am using laravel 10 and this is a blade file, Any suggestions I could try?

<div class="col-md-3 gridframe">
            <h3 class="text-center">Character Grid</h3>
            <div id="grid" class="row mx-auto">
            </div>
        </div>

<style>
    .gridframe {
        width: 300px;
        border: 1px solid black;
        overflow: hidden; 
    }

    .grid-cell {
        width: 50px;
        height: 50px;
        border: 1px solid black;
        text-align: center;
        position: relative;
        float: left;
    }

    .character {
        width: 30px;
        height: 30px;
        background-color: black;
        color: white;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;
        position: absolute;
        top: 10px;
        left: 10px;
    }

</style>

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
   function insertCharacter(nickname, hp) {
        var cells = $('.grid-cell');
        cells.each(function() {
            if (!$(this).children('.character').length) {
                var row = $(this).data('row');
                var col = $(this).data('col');
                $(this).append('<div class="character" data-hp="' + hp + '">' + nickname + '<br>' + hp + '</div>');
                return false; 
            }
        });

        // make characters draggable 
        $('.character').draggable({
            revert: 'invalid',
            zIndex: 100,
            start: function(event, ui) {
                $(this).css('cursor', 'pointer');
            },
            stop: function(event, ui) {
                $(this).css('cursor', 'auto');
            }
        });

        // make grid cells droppable
        $('.grid-cell').droppable({
            accept: '.character',
            drop: function(event, ui) {
                var character = ui.draggable;
                // var characterHP = character.data('hp');
                character.appendTo($(this)); 
            }
        });
    }

    $(document).ready(function() {
        $('#character-table tbody').on('DOMNodeInserted', 'tr', function() {
            var nickname = $(this).find('td:eq(0)').text();
            var hp = $(this).find('td:eq(1)').text();
            insertCharacter(nickname, hp);
        });

        $('#character-table tbody').on('DOMNodeRemoved', 'tr', function() {
            var nickname = $(this).find('td:eq(0)').text();
            $('.character').each(function() {
                if ($(this).text().includes(nickname)) {
                    $(this).remove();
                }
            });
        });

        var gridSize = 10; 
        var grid = $('#grid');
        for (var i = 0; i < gridSize; i++) {
            for (var j = 0; j < gridSize; j++) {
                $('<div class="grid-cell" data-row="' + i + '" data-col="' + j + '"></div>').appendTo(grid);
            }
        }
    });
    </script>```

WebGL 2.0 unsigned integer input variable

I’ve been trying to point an Uint32Array buffer to a uint input variable.

All the information I can find online says that it should be possible, yet I get the same error no matter what I do:

[.WebGL-0x62401b7e200] GL_INVALID_OPERATION: Vertex shader input type does not match the type of the bound vertex attribute.

Here’s my vertex shader:

#version 300 es
in vec4 a_ipos;
in uint a_cdata;
uniform vec2 ures;

void main() {
    uint x = a_cdata & 0x7C00u;
    uint y = a_cdata & 0x03E0u;
    uint z = a_cdata & 0x001Fu;

    vec4 pos = a_ipos + vec4(float(x), float(y), float(z), 1.);

    gl_Position = vec4(pos.x * ures.y / ures.x, pos.yzw);
}

And here’s my call to webgl to point the buffer to the attribute:

gl.bindBuffer(gl.ARRAY_BUFFER, chunkBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Uint32Array(chunkData), gl.STATIC_DRAW);
gl.enableVertexAttribArray(cdataloc);
gl.vertexAttribPointer(
    cdataloc,
    1,
    gl.UNSIGNED_INT,
    false,
    0,
    0
);

It seems gl.UNSIGNED_INT is not the same type as uint.
However the GLSL 300 ES reference card says that it’s a 32-bit unsigned integer.
MDN agrees that gl.UNSIGNED_INT is 32-bit unsigned integer.

I have no idea what I’m doing wrong. I’ve tried using gl.INT and in int ... and still nothing. Changing the precision of the integers to highp also doesn’t change anything. (provided highp would convert integers to 32-bit, which doesn’t seem to be the case).

Changing the type to float does work. But any other type I use doesn’t.

I also tried using gl.SHORT. This is to discard the theory that the int type in glsl might be 16-bit integer. Still the same error.

This question: WebGL: How to Use Integer Attributes in GLSL

Doesn’t solve my issue. As the documentation the answer provides is outdated. GLSL 1.00 ES doesn’t allow integers in attributes as per specification.

However, GLSL 3.00 ES specification doesn’t seem to care as long as the type is not one of the following: boolean, opaque, array, struct.

Using ytdl-core on the Front-End with ReactJS

I am trying to use ytdl-core with ReactJS on my Front-End to get the direct links of YouTube videos and then use them for getting the audio out of them, and video, and I also wanna put the audio on a tag. But the issue is that I get errors when I run:

useEffect(() => {
  (async () => {
    const stream = ytdl(LINK, {
      filter: "audioonly",
      format: "webm",
    }).on("error", (error) => console.log(error));
  })();
});

The error I get is: “Access to fetch at 'https://www.youtube.com/watch?v=blablablabl' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I would really appreciate some help regarding that matter

I’ve tried to use corsAnywhere but I get an error from ytdl-core saying “not a YouTube domain”.
This is how I tried to implement it:

useEffect(() => {
  (async () => {
    const stream = ytdl(`https://cors-anywhere.herokuapp.com/${LINK}`, {
      filter: "audioonly",
      format: "webm",
    }).on("error", (error) => console.log(error));
  })();
});

How do content attributes and IDL attributes interact?

I am trying to understand the short entry on IDL in the MDN Glossary.

In particular, I am struggling with the behavior described in the 4th paragraph under the “Content versus IDL attributes” header.

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for <input> elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute’s value will be "foobar". However, the type IDL attribute will return the string "text".

I will list a series of questions, along with my current ‘informed guesses’ in bulletpoints. I would like to either confirm my understanding, or expose my lack of it. Any input, clarification, or critique is appreciated (the questions may be fully off-base).


What does ‘their values as they are really used’ mean in this context (their default value [e.g, "text"], or the value set in a specific context [e.g, "foobar"])?

  • default (in the example, "test") – hence the final sentence of the quote.

Is the <input> element’s type an IDL or content attribute?

  • (technically both? but inasmuch as we access it through input.type it is an) IDL attribute

If IDL attributes are set using element.foo, doesn’t input.type qualify as setting an IDL attribute (in which case the "type" content attribute should not be "foobar")?

  • This misses a key behavior of IDL attributes w.r.t. content attributes: content atttributes can be set through IDL attributes, while leaving the IDL attribute itself unchanged (as hinted in the middle of this answer).

appendElement on an svg doesn’t render the new element automatically [duplicate]

I’m working on a Svelte+Vite project with a somewhat overgrown svg display component. A function is called that constructs an svg group with a circle in it’s inner HTML. In the future the inner text will be more complex, but this is just a placeholder.

svg = document.createElement('g')
svg.innerHTML = inner
total.appendChild(svg)

total references an existing svg group using the bind:this Svelte tag.

The issue is that when appendChild is called, nothing happens.
Other functions that manipulate the svg in other ways work just fine (setAttribute, removeChild, etc.)

There is nothing wrong with the svg contents. I can verify this by navigating to the element assigned to total in the web browser. When the function is called, the svg text appears under the right element just fine. If I right click on the total element in the browser, Copy->Inner HTML, then right click again, Paste->InnerHTML, the svg renders correctly. I’m using Firefox.

I do need to use the appendChild method here because the function adds an element dynamically, so I can’t solve this just by changing the function for something else. The rest of the display works fine and does not use appendChild because it usually renders things in larger chunks, such that it wouldn’t be efficient to draw individual children like this.

I could store a list of svg strings for all of the elements under this group, then redraw them all every time the list is updated (total.innerHTML = elems.join('n')), but that’s a last resort.

npm ERR! Fix the upstream dependency conflict, or retry this command with –force or –legacy-peer-deps

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]

npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I tried to install react-native-tesseract-ocr. But I faced the mentioned issue.

Styling a mapbox 3d buildings layer with external GeoJSON file

I’m able to see the buildings rendered in 3d using a Mapbox example, however, I want to change the fill color of the buildings using a property of a future from an external GeoJSON file. This is the first time I’ve worked with maps, so I little guidance will be great.

I have tried and succeed changing the color using feature-state, the click event and queryRenderedFeatures(), however, I’m not sure how to do that in the first render.

I’m expecting to see the map in the first load with the 3d buildings filled with different colors depending on the value of the grade that is inside of a GeoJSON file.

Maybe I’m missing some information but as I mentioned I’m new to maps and I’m not completely sure what I’m doing.

Thanks!

How can I modify my Chrome extension to display a custom confirmation modal before a file is uploaded?

I’m developing a Chrome extension and need it to prompt the user with a custom modal window asking for confirmation when they attempt to upload a file. Here’s the content.js script I’ve been working on:

function showModal(element) {
  const modal = document.createElement('div');

  modal.innerHTML = `
    <div style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:flex;justify-content:center;align-items:center;z-index:10000;">
      <div style="background:white;padding:20px;border-radius:5px;box-shadow:0 4px 6px rgba(0,0,0,0.1);">
        <p>Are you sure you want to upload the file?</p>
        <button id="confirmUpload">Yes</button>
        <button id="cancelUpload">No</button>
      </div>
    </div>
  `;

  document.body.appendChild(modal);

  // Handling confirmUpload
  document.getElementById('confirmUpload').addEventListener('click', () => {
    document.body.removeChild(modal);
  });

  // Handling confirmUpload
  document.getElementById('cancelUpload').addEventListener('click', () => {
    document.body.removeChild(modal);
    // Deleting the file from the element.files
    const dt = new DataTransfer()
    element.files = dt.files;
  });
}

// React to an event when a user uploads a file to the site 
document.addEventListener('change', (event) => {
    event.preventDefault();
    const element = event.target;
    
    if (element instanceof HTMLInputElement && element.type === 'file') {
        showModal(element);
    }
}, true);

The issue

The main issue I’m encountering is that the file starts uploading immediately upon selection, before the user can respond to the modal. This behavior defeats the purpose of seeking user confirmation.

Why common solutions won’t work

  1. Using event.stopPropagation() isn’t viable because it would necessitate custom upload logic for each site, which is impractical.
  2. Standard alert/prompt/confirm dialogs aren’t suitable either due to their lack of customization options; I intend to include features like file preview in the modal.

Given these constraints, does anyone have suggestions for a workaround or a different strategy to achieve the desired functionality? Or is it perhaps possible to achieve it with a completely different approach?

How to fix the errors with node virsion up

I have serious error occuring by version up.
I made a program in 18.x few years ago.
Now I version up node.js
And I have some errors.
Here are error messages:

ERROR in ./app/assets/scss/styles.scss (./node_modules/css-loader!./node_modules/sass-loader/dist/cjs.js!./app/assets/scss/styles.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (120)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
    at module.exports (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibbinding.js:13:13)
    at Object.<anonymous> (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibindex.js:14:35)
    at Module._compile (node:internal/modules/cjs/loader:1378:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
    at Module.load (node:internal/modules/cjs/loader:1212:32)
    at Module._load (node:internal/modules/cjs/loader:1028:12)
    at Module.require (node:internal/modules/cjs/loader:1237:19)
    at require (node:internal/modules/helpers:176:18)
    at getDefaultSassImpl (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:198:10)
    at Object.loader (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:80:29)
ERROR in ./app/containers/UserDashboard/assets/style.scss (./node_modules/css-loader!./node_modules/sass-loader/dist/cjs.js!./app/containers/UserDashboard/assets/style.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (120)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
    at module.exports (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibbinding.js:13:13)
    at Object.<anonymous> (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibindex.js:14:35)
    at Module._compile (node:internal/modules/cjs/loader:1378:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
    at Module.load (node:internal/modules/cjs/loader:1212:32)
    at Module._load (node:internal/modules/cjs/loader:1028:12)
    at Module.require (node:internal/modules/cjs/loader:1237:19)
    at require (node:internal/modules/helpers:176:18)
    at getDefaultSassImpl (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:198:10)
    at Object.loader (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:80:29)
ERROR in ./app/assets/scss/components/register.scss (./node_modules/css-loader!./node_modules/sass-loader/dist/cjs.js!./app/assets/scss/components/register.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (120)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
    at module.exports (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibbinding.js:13:13)
    at Object.<anonymous> (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibindex.js:14:35)
    at Module._compile (node:internal/modules/cjs/loader:1378:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
    at Module.load (node:internal/modules/cjs/loader:1212:32)
    at Module._load (node:internal/modules/cjs/loader:1028:12)
    at Module.require (node:internal/modules/cjs/loader:1237:19)
    at require (node:internal/modules/helpers:176:18)
    at getDefaultSassImpl (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:198:10)
    at Object.loader (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:80:29)
ERROR in ./app/components/CustomTable/components/pagination.scss (./node_modules/css-loader!./node_modules/sass-loader/dist/cjs.js!./app/components/CustomTable/components/pagination.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (120)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
    at module.exports (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibbinding.js:13:13)
    at Object.<anonymous> (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulesnode-sasslibindex.js:14:35)
    at Module._compile (node:internal/modules/cjs/loader:1378:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
    at Module.load (node:internal/modules/cjs/loader:1212:32)
    at Module._load (node:internal/modules/cjs/loader:1028:12)
    at Module.require (node:internal/modules/cjs/loader:1237:19)
    at require (node:internal/modules/helpers:176:18)
    at getDefaultSassImpl (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:198:10)
    at Object.loader (F:Data(D)DevProjectsBlockchainwallet_frontend_reactnode_modulessass-loaderdistindex.js:80:29)

Until now I haven’t error because of version up so I don’t know what I have to do.
How can I fix this problem?

I want build the project with out errors

Javascript does not redirect and time is stay same in Django Application. How to solve it?

Hi everyone I try to build web application with using django and js. It is kind of chat application there are rooms and each room have time after time is up. I want to delete room. While I making test, I realize if one user in room,other user in list page, room does not delete when 1 user in room and other list page. Time is stay 1 seconds How can ı solve this problem. Can you help me? Thank You.

room_detail_page

  function updateRemainingTime() {
        // Sunucuya AJAX isteği gönder
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/remaining-time/' + roomName + '/', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var remainingTime = JSON.parse(xhr.responseText);
                // Kalan süreyi güncelle
                document.getElementById('remaining-time').textContent = remainingTime.minutes + ':' + remainingTime.seconds;
                if (remainingTime.minutes <= 0 && remainingTime.seconds <= 0) {
                    deleteRoom(roomName);
                
            }
            }
        };
        xhr.send();
    }
    function deleteRoom(roomId) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/delete-room/' + roomId + '/', true);
    xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            window.location.href = '/home';
            location.reload()
        }
    };
    xhr.send();
}
setInterval(updateRemainingTime, 1000); 

room_list_page

function updateRemainingTime(roomId) {
        // Sunucuya AJAX isteği gönder
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/remaining-time/' + roomId + '/', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var remainingTime = JSON.parse(xhr.responseText);
                // Kalan süreyi güncelle
                var remainingTimeElement = document.getElementById('remaining-time-' + roomId);
            
                remainingTimeElement.textContent = remainingTime.minutes + ':' + remainingTime.seconds;
                if (remainingTime.minutes <= 0 && remainingTime.seconds <= 0 ) {
                    // If remaining time is 0 or negative, delete the room
                    deleteRoom(roomId);
                    
                }
                
            }
        };
        xhr.send();
    }
    // Belirli aralıklarla her oda için zamanı güncelle
    function deleteRoom(roomId) {
        // Sunucuya AJAX isteği gönder
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/delete-room/' + roomId + '/', true);
        xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');  // Add CSRF token if needed
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
               location.reload()
            }
        };
        xhr.send();
    }
    room_ids.forEach(function(roomId) {
        setInterval(function() { updateRemainingTime(roomId); }, 1000); // Her saniyede bir güncelle
    });

api.py

def remaining_time_api(request, room_id):
    room = Room.objects.get(id=room_id)
    remaining_time = room.remaining_time()
    seconds = remaining_time.seconds % 60
    minutes = (remaining_time.seconds // 60) % 60
    return JsonResponse({'minutes': minutes, 'seconds': seconds})

def delete_room(request, room_id):
    room = get_object_or_404(Room, id=room_id)
    room.delete()
    return redirect('/home')  

(Decided) QML How to do scrolable TextInput Wiyh SendMessageButton

i had a problem with scrolable TextInput and i haven’t seen any questions on the topic on the forums.
I was trying to decide problem with ListView, but because delegate blocks a function sendMSG it didn’t work out. Finally I used ScrollView and property contentWidth and it helped me.

My Code

 Rectangle{
            id:sendArea
                implicitWidth: userChat1.width*0.9
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.bottom:parent.bottom
                anchors.bottomMargin: 10
                implicitHeight: 60
                clip:true
                color: "#f4f3f7"
                radius: 16

    ScrollView{
        width: parent.width*0.78
        height: parent.height
        anchors.left: parent.left
        anchors.leftMargin: 10
        contentWidth: width

            TextInput
                {
                    autoScroll : true
                    id: youreTextInput
                    color: "#000000"
                    font.pointSize: 18
                    width: sendArea.width*0.74
                    anchors.left: parent.left
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.leftMargin: 10
                    wrapMode: Text.Wrap
                }
    }
            Button{
                id:sendButt
                onClicked: sendMSG();
            anchors.right: sendArea.right
            anchors.rightMargin: 10
            anchors.verticalCenter: sendArea.verticalCenter
            background: Rectangle{
            anchors.centerIn: parent
            color:"#29303C"
            height: sendArea.height*0.8
            width: height
            radius: height/2
                Text {
                    text: StackView.depth?"u15C6":"u15C6"
                    color: "#ffffff"
                    font.pointSize: 24
                    anchors.centerIn: parent
                }
            }

            }

            }
        function sendMSG(){
            if(youreTextInput.text == "")
            return;

           var isSender = Math.random() > 0.5;
            console.log("Sending mesage");
           var currentTime = new Date();
           var  hours = currentTime.getHours() < 10 ? "0" + currentTime.getHours() : currentTime.getHours();
           var  minutes = currentTime.getMinutes() < 10 ? "0" + currentTime.getMinutes() : currentTime.getMinutes();

            chatHistory.append({
                "sender": isSender,
                "message": youreTextInput.text,
                "time": hours + ":" + minutes
                                   });
            youreTextInput.text = "";

        }

I hope this helps to someone

Convert a flat array of objects to nested objects of different depths

I have an array of objects:

const flatData = [
  {
    "name": "Fish 1",
    "price": 15
  },
  {
    "name": "Super Fish 1",
    "price": 12,
    "family": "Super Fish family"
  },
  {
    "name": "Super Fish 2",
    "price": 17,
    "family": "Super Fish family"
  },
  {
    "name": "Super Fish 3",
    "price": 16,
    "family": "Super Fish family"
  },
  {
    "name": "Awful legged Fish 1",
    "price": 22,
    "family": "Awful Fish family",
    "sub_family": "Awful Fish with legs"
  },
  {
    "name": "Awful legged Fish 2",
    "price": 15,
    "family": "Awful Fish family",
    "sub_family": "Awful Fish with legs"
  },
  {
    "name": "Awful legged Fish 3",
    "price": 23,
    "family": "Awful Fish family",
    "sub_family": "Awful Fish with legs"
  },
  {
    "name": "Awful blue dotted Fish 1",
    "price": 10,
    "family": "Awful Fish family",
    "sub_family": "Awful Fish with blue dots"
  },
  {
    "name": "Awful blue dotted Fish 2",
    "price": 11,
    "family": "Awful Fish family",
    "sub_family": "Awful Fish with blue dots"
  }
]

And I wanted to convert it to a nested array of objects:

const nestedData = [
  {
    "id": "0",
    "name": "Fish 1",
    "price": 15
  },
  {
    "id": "1",
    "name": "Super Fish family",
    "selected": -1,
    "family": [
      {
        "id": "0",
        "name": "Super Fish 1",
        "price": 12
      },
      {
        "id": "1",
        "name": "Super Fish 2",
        "price": 17
      },
      {
        "id": "2",
        "name": "Super Fish 3",
        "price": 16
      }
    ]
  },
  {
    "id": "2",
    "name": "Awful Fish family",
    "selected": -1,
    "family": [
      {
        "id": "0",
        "name": "Awful Fish with legs",
        "selected": -1,
        "family": [
          {
            "id": "0",
            "name": "Awful legged Fish 1",
            "price": 22
          },
          {
            "id": "1",
            "name": "Awful legged Fish 2",
            "price": 15
          },
          {
            "id": "2",
            "name": "Awful legged Fish 3",
            "price": 23
          }
        ]
      },
      {
        "id": "1",
        "name": "Awful Fish with blue dots",
        "selected": -1,
        "family": [
          {
            "id": "0",
            "name": "Awful blue dotted Fish 1",
            "price": 10
          },
          {
            "id": "1",
            "name": "Awful blue dotted Fish 2",
            "price": 11
          }
        ]
      }
    ]
  }
]

I thought I could break the problem down into a series of less complicated problems but I’m stuck at this step. I found solutions based on splitting a string but my flat file is different. The presence of “family” and “sub_family” and I can deduce depth information from one single value…

Is there a js library that would make this easier?