How to add item to each level of a nested array

I have infinite levels array in each object and I want to add “id” based on levels. Suppose if level 1 then id should be 1 and level two then id will be 2 etc.

{
"name": "Anything2",
"code": "SS_1",
"levels": [
    {
        "levelName": "New level",
        "levels": [
            {
                "levelName": "New Level2",
                "levels": [
                    {
                        "levelName": "New Level2",
                        {
                            "levelName": "New Level2",
                            "levels": [
                                {
                                    "levelName": "New level"
                                }
                            ]
                        }
                    },
                    {
                        "levelName": "New Level2",
                    },
                    {
                        "levelName": "New Level2",
                    }
                ]
            },
            {
                "levelName": "New Level2"
            },
            {
                "levelName": "New Level2",
                "levels": [
                    {
                        "levelName": "New level"
                    }
                ]
            }
        ]
    }
]

}

I want to convert the above array into below new array. I have tried using for loop but its not working I am not getting expected data. I want to add “id” based on levels. Suppose if level 1 then id should be 1 and level two then id will be 2 etc.

{
"name": "Anything2",
"code": "SS_1",
"levels": [
    {
        "id": 1,
        "levelName": "New level",
        "levels": [
            {
                "id": 2,
                "levelName": "New Level2",
                "levels": [
                    {
                        "id": 3,
                        "levelName": "New Level2",
                        {
                            "levelName": "New Level2",
                            "levels": [
                                {
                                    "id": 4,
                                    "levelName": "New level"
                                }
                            ]
                        }
                    },
                    {
                        "id": 3,
                        "levelName": "New Level2",
                    },
                    {
                        "id": 3,
                        "levelName": "New Level2",
                    }
                ]
            },
            {
                "id": 2,
                "levelName": "New Level2"
            },
            {
                "id": 2,
                "levelName": "New Level2",
                "levels": [
                    {
                        "id": 3,
                        "levelName": "New level"
                    }
                ]
            }
        ]
    }
]

}

trying update the content of array with useState, but it doesn’t work

I’m new and practicing react.js.
I’m trying to update the content of array with useState by clicking a send-button, but it doesn’t work as I expect.


Below is problem I’m having. Idk to add date and number in a row.
enter image description here

also, below is what I expect.
enter image description here

code:

import React, { useState, useRef } from 'react';
import classes from '../style/LineChart.module.css'
import { Button, Input } from '@chakra-ui/react';
import { Line } from 'react-chartjs-2'
import {
 Chart as ChartJS,
 CategoryScale,
 LinearScale,
 PointElement,
 LineElement,
 Title,
 Tooltip,
 Legend,
} from "chart.js";

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, 
                Tooltip, Legend);

const LineChart = () => {
 const [numData, setNumData] = useState([0]);
 const [date, SetDate] = useState(['']);

 const calVal = useRef(null);
 const chooseDate = useRef(null);


 const onClick = () => {
    setNumData([calVal.current.value]);
    calVal.current.value = '';

    SetDate([chooseDate.current.value]);
    // SetDate([...date, chooseDate.current.value])
    chooseDate.current.value = '';
}

const data = {
    labels: [date],
    datasets: [
        {
            label: 'How many todos can you achieve?',
            fill: true,
            lineTension: 0.1,
            backgroundColor: 'rgba(75,192,192,0.4)',
            borderColor: 'rgba(75,192,192,1)',
            borderCapStyle: 'round',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'square',
            pointBorderColor: 'rgba(75,192,192,1)',
            pointBackgroundColor: '#eee',
            pointBorderWidth: 10,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: 'rgba(75,192,192,1)',
            pointHoverBorderColor: 'rgba(220,220,220,1)',
            pointHoverBorderWidth: 1,
            pointRadius: 1,
            pointHitRadius: 10,
            data: [numData]
        }
    ]
};

const checkOfDelete = () => {
    let result = window.confirm('Reset. ok?')
    
    if(result) {
        console.log('Delete.');
    } else {
        alert('fail.')
    }
};

return (
    <div mt='2'>
        <Line data={data}/>
        <Input className={classes.input} ref={chooseDate} variant='outline' w='40%' ml='30%' mb='3' mt='3' borderRadius='15px' type='text' label='date' placeholder='Date'/>
        <Input className={classes.input} ref={calVal} variant='outline'  w='54%' ml='23%' mb='3' borderRadius='15px' type='number' label='number' placeholder='How many?'/>
        <br/>
        {data.labels.length < 8 ? <Button colorScheme='teal' ml='21%' mr='2' onClick={onClick}>Send</Button> : <p>date is full.</p>}
        <Button colorScheme='teal' onClick={checkOfDelete} >Reset</Button>
    </div>
)
};

export default LineChart;

To work well, I’ve tried this way.

const data = {
    labels: [calVal.current.value ,...date],
    datasets: [
        {
            label: 'How many todos can you achieve?',
            fill: true,
            lineTension: 0.1,
            backgroundColor: 'rgba(75,192,192,0.4)',
            borderColor: 'rgba(75,192,192,1)',
            borderCapStyle: 'round',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'square',
            pointBorderColor: 'rgba(75,192,192,1)',
            pointBackgroundColor: '#eee',
            pointBorderWidth: 10,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: 'rgba(75,192,192,1)',
            pointHoverBorderColor: 'rgba(220,220,220,1)',
            pointHoverBorderWidth: 1,
            pointRadius: 1,
            pointHitRadius: 10,
            data: [chooseDate.current.value,...numData]
        }
    ]
};

but if this, I got error like: “Uncaught TypeError: Cannot read properties of null (reading ‘value’)”
Can someone please help me? I am sorry if it is very basic but I am only starting out..

How to implement row level access control in PostgreSQL using Sequelize?

I am building a multi-tenant backend using Node, Express, PostgreSQL and Sequelize. All of my tenant’s data is stored in the same table. Right now, I am using the WHERE clause to filter data and restrict one tenant’s data from others but I would like to add another layer of security using the row-level access control feature of PostgreSQL. I found this article very helpful but it does not cover the implementation in NodeJS.

Select moment to start fade in animation JavaScript

I wrote a piece of code with jQuery to start a fade-in animation on some content I have on my new portfolio website. The code works and the animation appears. Just the moment the animation starts is unlogic. In my mobile version, the animation starts when I’m halfway in the p text.

Any options to manipulate this within this code to select a certain amount of pixels from the innerHeight before the animation starts? Let’s say when the objectTop reaches windowMiddle? Comments are much appreciated.

$(window).on("load", function() {
  $(window).scroll(function() {
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();

    $(".fade").each(function() {
      var objectBottom = $(this).offset().top + $(this).outerHeight();
      if (objectBottom < windowBottom) { //object shows on scroll
        if ($(this).css("opacity") == 0) {
          $(this).fadeTo(500, 1);
        }
        // } else {
        //   object fade away scrolling up
        //   if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);
        // }
      }
    });
  }).scroll();
});
.fade {opacity: 1; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p> Bladibladibla </p>
</div>

I have a time array I want to group by on another key value having start time and end time using typescript

Time_Array = ["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00"]

Input = [
{
“hour”: “00:00”,
“gID”: 10
},
{
“hour”: “01:00”,
“gID”: 10
},{
“hour”: “02:00”,
“gID”: 10
},{
“hour”: “07:00”,
“gID”: 30
},{
“hour”: “08:00”,
“gID”: 32
},{
“hour”: “11:00”,
“gID”: 40
},{
“hour”: “12:00”,
“gID”: 40
},{
“hour”: “15:00”,
“gID”: 55
},
{
“hour”: “17:00”,
“gID”: 59
},
]

Expected_Output = [{“start_time” : “00:00”, “end_time”:”03:00″, “gID”:10},{“start_time” : “07:00”, “end_time”:”08:00″, “gID”:30},{“start_time” : “08:00”, “end_time”:”09:00″, “gID”:32}
{“start_time” : “11:00”, “end_time”:”13:00″, “gID”:40},{“start_time” : “15:00”, “end_time”:”16:00″, “gID”:55},{“start_time” : “17:00”, “end_time”:”18:00″, “gID”:59}]

Generate a const typed object in TypeScript

I am trying to generate a const typed object by passing in a string I want to use as the type, is this possible, I have tried the below and it’s bringing out the wrong type.

const test = <T> (name: T) => {
  const hi: { name: T } = {
    name
  } as const
  return hi
}

const test1 = test('hello')

I’d like this to be of type

{
    name: 'hello';
}

But instead it’s of type

{
    name: string;
}

Convert first letter of a string to uppercase

I have this code where the input of first-name last-name will be converted to lowercase then the first letters of each word will be converted to uppercase and then swap place.

However, I ran into an inconvenience where special characters(not certain with the term) were not being processed.

Input: oNdřej rasZka
Desired output: Raszka,Ondřej
What I’m getting: OndŘEj Raszka

The “ŘE” of OndŘEj was not processed properly same with other available special characters, is there any way to solve this?

<div>
  <textarea cols="50" rows="5" id="fullName" class= ""></textarea>
</div>

<button id="splitName">Click</button>
<div>
  <br>
</div>
<div class= "border" id="result"></div>

var splitName = document.getElementById("splitName");

splitName.onclick = function() {
  document.getElementById("result").innerHTML = '';

        var value = document.getElementById("fullName").value;
  
  
  //CASE CONVERT//
            var value2 = value.toLowerCase();
            value2 = value2.replace(/b./g, function(m){ return m.toUpperCase(); });

        

    value2.split('n').forEach(fullname => {
    var spaceIndex = fullname.indexOf(" ");
    var firstname;
    var lastname;
    if (spaceIndex == -1) {
      lastname = fullname;
      lastname = "";
    } else {
      firstname = fullname.substring(0, spaceIndex);
      lastname = fullname.substr(spaceIndex + 1);       
    }

        document.getElementById("result").innerHTML += lastname + " " + firstname+ "<br>";
             


  });
};

Thanks a lot.

How to sum a array like a Excel Pivot where two keys must macht?

I try to sum all “Menge” and “Fehler” values where “Datum” AND “Material” must match. The result should look like an Excel Pivot.

This is my code so far, but I don’t know how to add the second key “Material” that also must match .
I hope you can understand what I try to explain.

var arr = [{
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 100,
  "Fehler": 5
}, {
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 5,
  "Fehler": 1
}, {
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 6,
  "Fehler": 65
}, {
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "222",
  "Menge": 10,
  "Fehler": 5
}, {
  "Datum": {
    "date": "2000-01-02 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "444",
  "Menge": 29,
  "Fehler": 1
}, {
  "Datum": {
    "date": "2000-01-02 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 1,
  "Fehler": 1
}]

const result = Object.values(arr.reduce((acc, obj) => {
  const [Datum] = obj.Datum.date.split(' ');
  const Menge = (acc[Datum] ?.Menge + obj.Menge) || obj.Menge;
  const Fehler = (acc[Datum] ?.Fehler + obj.Fehler) || obj.Fehler;
  acc[Datum] = {
    Datum,
    Menge,
    Fehler
  };
  return acc;
}, {}));

console.log(result)

But the result should look like:

[{
    "Datum": "2000-01-01",
    "Material": "123",
    "Menge": 111,
    "Fehler": 71
  },
  {
    "Datum": "2000-01-01",
    "Material": "222",
    "Menge": 10,
    "Fehler": 5
  },
  {
    "Datum": "2000-01-02",
    "Material": "444",
    "Menge": 29,
    "Fehler": 1
  },
  {
    "Datum": "2000-01-02",
    "Material": "123",
    "Menge": 1,
    "Fehler": 1
  }
]

Thank you very much

How to set cookie expiry age and path in Javascript? [duplicate]

I am making Cookie Consent for website and the only problem I have right now is that Cookie is stored in that session only, and I also want to set path to my root domain.
Currently my JS is like this:

const cookieStorage = {
    getItem: (item) => {
        const cookies = document.cookie
            .split(';')
            .map(cookie => cookie.split('='))
            .reduce((acc, [key, value]) => ({ ...acc, [key.trim()]: value }), {});
        return cookies[item];
    },
    setItem: (item, value) => {
        document.cookie = `${item}=${value};`
    }
}

const storageType = cookieStorage;
const consentPropertyName = 'Cookie By: RohanPhuyal ';
const shouldShowPopup = () => !storageType.getItem(consentPropertyName);
const saveToStorage = () => storageType.setItem(consentPropertyName, true);

window.onload = () => {

    const acceptFn = event => {
        saveToStorage(storageType);
        consentPopup.classList.add('hidden');
    }
    const consentPopup = document.getElementById('consent-popup');
    const acceptBtn = document.getElementById('accept');
    acceptBtn.addEventListener('click', acceptFn);

    if (shouldShowPopup(storageType)) {
        setTimeout(() => {
            consentPopup.classList.remove('hidden');
        }, 1000);
    }

};

How can I add expiry time (age) on cookie and also set path=/ ?

How to restrict date of Birth from selecting future date

<script type="text/javascript">

 //Create references to the dropdown's
const yearSelect = document.getElementById("year");
const monthSelect = document.getElementById("month");
const daySelect = document.getElementById("day");

const months = ['January', 'February', 'March', 'April', 
'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December'];

//Months are always the same
(function populateMonths(){
    for(let i = 0; i < months.length; i++){
        const option = document.createElement('option');
        option.textContent = months[i];
        monthSelect.appendChild(option);
    }
    monthSelect.value = "January";
})();

let previousDay;

function populateDays(month){
    //Delete all of the children of the day dropdown
    //if they do exist
    while(daySelect.firstChild){
        daySelect.removeChild(daySelect.firstChild);
    }
    //Holds the number of days in the month
    let dayNum;
    //Get the current year
    let year = yearSelect.value;

    if(month === 'January' || month === 'March' || 
    month === 'May' || month === 'July' || month === 'August' 
    || month === 'October' || month === 'December') {
        dayNum = 31;
    } else if(month === 'April' || month === 'June' 
    || month === 'September' || month === 'November') {
        dayNum = 30;
    }else{
        //Check for a leap year
        if(new Date(year, 1, 29).getMonth() === 1){
            dayNum = 29;
        }else{
            dayNum = 28;
        }
    }
    //Insert the correct days into the day <select>
    for(let i = 1; i <= dayNum; i++){
        const option = document.createElement("option");
        option.textContent = i;
        daySelect.appendChild(option);
    }
    if(previousDay){
        daySelect.value = previousDay;
        if(daySelect.value === ""){
            daySelect.value = previousDay - 1;
        }
        if(daySelect.value === ""){
            daySelect.value = previousDay - 2;
        }
        if(daySelect.value === ""){
            daySelect.value = previousDay - 3;
        }
    }
}

function populateYears(){
    //Get the current year as a number
    let year = new Date().getFullYear();
    //Make the previous 100 years be an option
    for(let i = 0; i < 101; i++){
        const option = document.createElement("option");
        option.textContent = year - i;
        yearSelect.appendChild(option);
    }
}

populateDays(monthSelect.value);
populateYears();

yearSelect.onchange = function() {
    populateDays(monthSelect.value);
}
monthSelect.onchange = function() {
    populateDays(monthSelect.value);
}
daySelect.onchange = function() {
    previousDay = daySelect.value;
}

//Create references to the dropdown’s
const yearSelect = document.getElementById(“year”);
const monthSelect = document.getElementById(“month”);
const daySelect = document.getElementById(“day”);

const months = [‘January’, ‘February’, ‘March’, ‘April’,
‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’,
‘November’, ‘December’];

//Months are always the same
(function populateMonths(){
for(let i = 0; i
for(let i = 1; i

Checking if date is valid in javascript get `RangeError: Invalid time value` testing it

I created this function to check if the date is valid or not:

function isValidDate(dateObject){
  if(!dateObject) return;
  
    return new Date(dateObject).toString() !== 'Invalid Date';
}
console.log(isValidDate('not valid time')) // false

This function works good, but trying to test it with jest i get this error: RangeError: Invalid time value, i suppose that this happens because the argument is a string and it pass the if(!dateObject) return;.
Question: How to avoid this error in my case?

Can’t redirect to url by javascript function

I need a button, which lead up in url path like this:

from /host/elements/1
to /host/elements

I have a link in my html:

<a href="javascript:go_backward()"> </a>

And a javascript function:

function go_backward() {
    var url = window.location.href;
    var page = url.substring(0, url.lastIndexOf('/'))
    window.location.assign(page);
    return false;
}

But when i click the button i only get desired url printed, without correct redirect.
Why cat it be so?

jquery – get a value in mix radio button

Would you like to check what wrong in my code, I have 2 group radio button when I click the radio button variable r not have a value :

<script>
$(document).ready(function() {
    var s = 0;
    var l = 0;
    var r = 0;

    $('input[type=radio][name="saverity"]').change(function() {
        s = $(this).val();
        console.log(s);
    });

    $('input[type=radio][name="likehood"]').change(function() {
        l = $(this).val();
        console.log(l);
    });

    r = s * l;
    console.log(r);

});

Thank you very much.

Variable not being passed from front end to backend

I’m scratching my head at this problem, I’m implementing Instagrams basic display API using Wix’s new editor-x. My code works if I run it on the client side, I get an access token, however it doesn’t when I import the getAccessToken function from the server side, the function runs but I get an invalid auth code.

I think there maybe an issue passing the code variable?

frontend code:

import wixLocation from 'wix-location'
import {getAccessToken} from 'backend/instagram'
let query = wixLocation.query; //get auth code from URL param
    let code = query.code
    console.log(code) //check code is correct
    if(code){
        const token = await getAccessToken(code) //request accesstoken
        console.log(token) //log token
        }

backend code:

import {fetch} from 'wix-fetch'
export async function getAccessToken(code) {
    const url = "https://api.instagram.com/oauth/access_token"
    const options = {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: `client_id=id&client_secret=secret&grant_type=authorization_code&redirect_uri=uri&code=${code}`
    }
    try {
        const data = await fetch(url,options)
        const token = await data.json()
        return token
    } catch(error) {
        return error
    }
}