convert complex and nested json to table in excel using javascript

I am trying to convert a JSON in which some items can contains arrays as well. I get a very nicely structured table if I convert my JSON in json2table.com. I want similar table to be created in Excel using Javascript/nodejs. I tried some packages like ‘json2xls’, ‘xlsx’ etc. However I am not getting the desired output. Here’s my JSON.

JSON:

{
"name":"Gopi",
"id":"01",
"subjects":[{
"subject":"maths",
"marks":"84"
},
{
"subject":"science",
"marks":"85"
}],
"teachers":{
"name": "teacherA"
}
}

enter image description here

I am using below code. But I see [object Object],[object Object] under the column ‘subjects’

var json2xls = require('json2xls');
const fs = require('fs')
var json = {
  "name": "Gopi",
  "id": "01",
  "subjects": [{
    "subject": "maths",
    "marks": "84"
  },
  {
    "subject": "science",
    "marks": "85"
  }],
  "teachers": {
    "name": "teacherA"
  }
}
var xls = json2xls(json);
fs.writeFileSync('stackof.xlsx', xls, 'binary');

Acomodar elementos de izquierda a derecha [closed]

Estoy desarrollando una barra de busqueda, ya logre que funcione correctamente. mi problema es que los articulos aparecen listados uno debajo del otro cuando yo quiero que aparezcan de izquierda a derecha. Si alguien pudiera ayudarme con eso, lo agradeceria mucho.

trato de que los productos de mi lista se acomoden de izquierda a derecha sin que mi barra de busqueda deje de funcionar

Started studying code and January, and I lost a lot of time on deprecated tutorials

Im new into programming,I started studying really hard, 10-14 hrs a day, and I made some bad decisions buying online deprecated courses. I took the JS-NodeJS-Rect/Vue path. For that I thought UDEMI was ok and I got the 2023 full stack course. Now it’s been ok so far, but EJS and mongoose are deprecated and I can’t go along with the course. Are there any resources you can recommend me???? Thanks!!!!!

Some up to date guided way to learn

Get type for an object’s values where each object is of type , and each function have different argument

The object looks like this

export const templates = {
  [EventType.EventType1 + OutputSources.Email]: (params: { documentName: string; link: string }) => {
    return "some html data";
  },
  [EventType.EventType2 + OutputSources.Email]: (params: { documentName: string }) => {
    return "some html data";
  },
  [EventType.EventType1 + OutputSources.Notification]: (params: { documentName: string }) => {
    return "some html data";
  },
} as const;

I want to have a type that contains parameters of each of these function as a union, for example the result for above will look like.
type possibleFunctionArgs = {documentName:string,link:string} | {documentName:string}

What I’ve already tried and failed
type lastFailingAttemptToGetTypes = Parameters<typeof templates[keyof typeof templates]>
For the above code I’m always getting only {documentName:string,link:string} , always getting the one with highest number of parameters

Is there a way in Zod to create a new schema from an object schema by type?

Let’s say I have the following example schema:

const Z_GlobalSettings = z.object({
  crust: z.enum(["thin", "thick"]).default("thin"),
  toppings: z.array(z.string()).min(1).max(5).default(["cheese"]),
  sauce: z.enum(["marinara", "bbq", "ranch"]).default("marinara"),
  delivery_time: z.string().optional(),
  order_notes: z.string().max(50).optional(),
  contact_email: z.string().email().optional(),
  setting_1: z.boolean(),
  setting_2: z.boolean().optional(),
});

type GlobalSettings = z.infer<typeof Z_GlobalSettings>;

How can I programmatically extract the types that contain booleans, or whichever arbitrary type I’m looking for? For example, if I want the booleans from the schema, I’d want my new schema to look like:

const Z_OnlyBoolean = z.object({
  setting_1: z.boolean(),
  setting_2: z.boolean().optional(),
});

I was initially able to accomplish this using Typescript:

type BooleanSettings = {
  [K in keyof GlobalSettings as GlobalSettings[K] extends boolean | undefined
    ? K
    : never]?: boolean;
};

However, this wasn’t working when I wanted to differentiate between z.string() and z.enum(["example1", "example2"]), since they’d both come through as strings. This is why I’m hoping to find a way to filter a schema by type since Zod is keeping track of the difference between strings and enums, but the only way I can find in the documentation is to use the .pick() method and choose them one-by-one. This won’t be great if I add properties in the future, since I’ll need to update the filtered schema as well, and won’t be great for usability since I’ll need to make a new schema for every type I want to extract.

Any ideas on how to accomplish this?

is there a way to use getElementbyid but for multiple of the same id’s

I’m trying to use a function that appends a text onto an answer choice on a multiple choice quiz but I can only seem to access the first answer value.

<!doctype html>
<html>
    
    <head>
        <meta charset="utf-8" />
        <title>name</title>

    </head>
    <h1>
        name
    </h1>
    <body style="background-color:rgb(73, 88, 83);">

            <div id="question1">
                <p>1. which planet is considered earth's sister planet?</p>
                <a href = "#">
                    <p id = "answer" value = "wrong">a. moon</p>
                </a>
                <a href = "#">
                    <p id = "answer"  value = "correct">b. venus</p>
                </a>
                <a href = "#">
                    <p id = "answer" value = "wrong">c. mars</p>
                </a>
            </div>

            <div id="question2">
                <p>2. when did apollo 11 land?</p>
                <a href = "#"> 
                    <p id = "answer" value = "correct">a. 1969</p>
                </a>
                <a href = "#">
                    <p id = "answer"  value = "wrong">b. 1970</p>
                </a>
                <a href = "#">
                    <p id = "answer" value = "wrong">c. 1968</p>
                </a>
            </div>

            <div id="question3">
                <p>3. which is the planet mars?</p>
                <a href = "#">
                    <p id = "answer" value = "wrong">a. <img src = "https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg" width="50" height="50"> </p>
                </a>
                <a href = "#">
                    <p id = "answer"  value = "wrong">b. <img src = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Africa_and_Europe_from_a_Million_Miles_Away.png" width="50" height="50"> </p>
                </a>
                <a href = "#">
                    <p id = "answer" value = "correct">c. <img src = "https://upload.wikimedia.org/wikipedia/commons/0/02/OSIRIS_Mars_true_color.jpg" width="50" height="50"> </p>
                </a>
            </div>

            <div class="buttons">
                <button id="reset-button"> Reset </button>
            </div>


            <script>
                const reset = document.getElementById("reset-button")
                var clicked = document.getElementById("answer")
                var text = document.createTextNode(" correct")
                var text_2 = document.createTextNode(" wrong")
        
                reset.addEventListener('click', resetquestions)
                clicked.addEventListener('click', giveAnswer)
                
    
                function giveAnswer() {
                    if(clicked.value === "correct") {
                        clicked.appendChild(text)
                    }
                    else {
                        clicked.appendChild(text_2)
                    }
                }

                function resetquestions() {
                    if(clicked.value === "correct") {
                        text.remove()
                    }
                    else {
                        text_2.remove()
                    }
                }
            </script>
    </body>
</html>

I want to be able to append a correct or wrong text to every answer choice that I click. I tried changing the ID’s to answer_1_1, answer_1_2 and adding an event listener to them individually but unfortunately I wasn’t even able to get the first response’s answer anymore. How can I fix this? sidenote: i’m not allowed to use buttons or input for the answer choices.

The annotation message does not appear. with Chart.js , react-chart-js , and chartjs-plugin-annotation

Show code

import React from "react";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Line } from "react-chartjs-2";

import annotationPlugin from "chartjs-plugin-annotation";

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

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: "top",
    },
    title: {
      display: true,
      text: "Chart.js Line Chart",
    },
    annotation: {
      annotations: {
        line1: {
          adjustScaleRange: true,
          drawTime: "afterDatasetsDraw",
          type: "line",

          scaleID: "x",
          value: 1,
          borderColor: "rgba(104,1)",

          label: {
            enabled: true,
            content: "Hi !!",
            backgroundColor: "rgba(255, 26, 104, 0.8)",
            color: "black",
          },
        },
      },
    },
  },
};

const labels = [1, 2, 3, 4];

export const data = {
  labels,
  datasets: [
    {
      label: "My First Dataset",
      data: [65, 59, 80, 81, 56, 55, 40],
      fill: false,
      borderColor: "rgb(75, 192, 192)",
      tension: 0.1,
    },
  ],
};

export function ChartPrueba() {
  return (
    <div>
      <h1>Example react-chartjs-2 Chart with the annotation plugin</h1>
      <Line options={options} data={data} />;
    </div>
  );
}

I tried disabling tailwindcss and importing it directly into the app, I use Vite and these are the dependencies

 "dependencies": {
    "chart.js": "^4.2.1",
    "chartjs-plugin-annotation": "^2.2.1",
    "react": "^18.2.0",
    "react-chartjs-2": "^5.2.0",
    "react-dom": "^18.2.0"
  },


Stack asks me to put more words I don’t know why.
Everything is already there so I add random words.
Stack asks me to put more words I don’t know why.
Everything is already there so I add random words.
Stack asks me to put more words I don’t know why.
Everything is already there so I add random words.
Stack asks me to put more words I don’t know why.
Everything is already there so I add random words.
Stack asks me to put more words I don’t know why.
Everything is already there so I add random words.
Stack asks me to put more words I don’t know why.
Everything is already there so I add random words.

}

How to receive push notifications on my iPhone with IOS 16.4

Hello everyone I hope you are well recently there was an update on iOS that now allows you to receive push notifications from a site on iPhone with the version IOS 16.4

Here is a piece of code that I wanted to try on my iPhone however I have no popup to display when I click on the button my iPhone has well the update 16.4 in the settings of my iPhone I gave him access to receive external notifications

Settings>Safari > Advanced>Experimental Features> (accept push api)

I would like to know if someone succeeded in setting up push notifications on safari on iPhone please
Here is my code below

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button class="notify-btn">Click me </button>
</body>
<script src="./main.js"></script>
</html>

main.js

document.querySelector(".notify-btn").addEventListener("click", function() {

  Notification.requestPermission().then(function(result) {
    if (result !== "granted") {
      console.log("No notification permission granted!");
      return;
    } else {
      console.log("Button clicked");
      new Notification("This is a notification", {
        body: "This is the body of the notification",
        icon:
          "https://cdn4.iconfinder.com/data/icons/flat-brand-logo-2/512/medium-512.png",
      });
    }
  });
});

result on my Mac
image

Use mouseover for a list of products

I have multiple product cards within a division. I want to display the relevant information when the mouse is moved on each card, and not to display the information whenever the mouse is out.

<div class="row holderCard d-flex">
<div class="col-md-4 col-sm-12 card">
            <div class="holderDetailsImg">
                <div>
                    <div class="coverGradient d-none"></div>
                    <img src="img/zahedan.jpg" alt="Avatar">
                </div>
                <div class="infoImg d-none">
                    <span class="badgesLike"><i class="fa fa-heart-o"></i></span>
                    <p class="titleDetailesImg">یک متن آزمایشی داخل ان است</p>
                    <p class="descriptionDetailesImg">یک متن آزمایشی داخل آن وجود دارد که با هم هست</p>
                    <span class="badgesTags">مسجد مکی زاهدان</span>
                    <div class="badgesStar">
                        <span class="fa fa-star checked "></span>
                        <span class="fa fa-star checked "></span>
                        <span class="fa fa-star checked "></span>
                        <span class="fa fa-star "></span>
                        <span class="fa fa-star "></span>
                    </div>
                </div>
            </div>
            <div class="container">
                <span class="badges">2</span>
                <p class="captionCard small">مجموعه ای از بهترین مکان های گردردشگری</p>
            </div>
        </div>
        <div class="col-md-4 col-sm-12 card">
            <div class="holderDetailsImg">
                <div>
                    <div class="coverGradient d-none"></div>
                    <img src="img/yazd.jpg" alt="Avatar">
                </div>
                <div class="infoImg d-none">
                    <span class="badgesLike"><i class="fa fa-heart-o"></i></span>
                    <p class="titleDetailesImg">یک متن آزمایشی داخل ان است</p>
                    <p class="descriptionDetailesImg">یک متن آزمایشی داخل آن وجود دارد که با هم هست</p>
                    <span class="badgesTags">بادگیرهای یزد</span>
                    <div class="badgesStar">
                        <span class="fa fa-star checked "></span>
                        <span class="fa fa-star checked "></span>
                        <span class="fa fa-star checked "></span>
                        <span class="fa fa-star "></span>
                        <span class="fa fa-star "></span>
                    </div>
                </div>
            </div>
            <div class="container">
                <span class="badges">2</span>
                <p class="captionCard small">مجموعه ای از بهترین مکان های گردردشگری</p>
            </div>
        </div>
</div>
I have written the mouseover part using the forEach and a condition to have the d-none class. My problem is that when the mouse is placed on any of the cards, only d-none of the first card is removed.

I can’t understand where the problem is.
Because when there is an alert inside the function, all the information cards are shown with float. But the d-none class is not removed

let holderDetailsImg= document.querySelectorAll('.holderDetailsImg')
let coverGradient= document.querySelector('.coverGradient')
let infoImg= document.querySelector('.infoImg')


holderDetailsImg.forEach(function (holderDetailsImg){
    holderDetailsImg.addEventListener("mouseover", mouseOver);
    function mouseOver() {
        if(coverGradient.classList.contains('d-none') || infoImg.classList.contains('d-none')){
            coverGradient.classList.remove('d-none');
            infoImg.classList.remove('d-none');

        }
    }
})

and not css codes. i only add d-none on tags

When using gatsby-source-filesystem’s createRemoteFileNode can I access the publicURL of the downloaded file?

I’m working on plugin for Gatsby.

When using createRemoteFileNode to download a remote file (in my case an image) a File object is returned, however that object doesn’t appear to have any information about where the file was downloaded to. This is added much later in the lifecycle by a resolver and can then be accessed on a File node using the publicURL field.

Is there any way to access the local location of the downloaded file from within JavaScript either from the File object returned by createRemoteFileNode or through another API. Ideally I want to know where the file was downloaded as soon as createRemoteFileNode returns.

Chrome Extesions. If I only using content_scripts. Do I need permisions “host_permisions” and “scripting”?

I read that i need host_permissions or scripting if i “inject programmatically” the content_scritps but the examples show that they use background.js code to inject the script, i don’t use that, i don’t even have a background.js. My extension only has a few functions and events. Yes, the events and functions change the html of page.

In dev mode the extension works without host_permisions, but when I send it to revision, they ask for host_permisions justification anyway

Unable to get length value of an array in Node Red Javascript

I would like to know the length of an array read inside a function in NodeRed using Javascript but it is not displaying/ returning any value. can someone help me here.

enter image description here

Here is the code inside the function block in Node-Red

let j = 0;
let array1 = { payload: msg.payload };

j = array1.length;

return j;

I do not see any return value for J. any help ?

I was expecting a value of 50 for J to be displayed on Nodered debug console.

How can I add the .active class to my menu’s tags based on the current url?

I’m building a custom menu for my website. What I want to do here is add an active class to highlight the menu item when it matches the current page link.

Example: if the user is on the page https://mywebsite.it/explore-docs then .link_expdocs gains the active class.

I managed to do this with some Javascript, but I don’t like what came out. I’ve iterated the code many times and I don’t think it’s a good practice.

Is there a better and shorter practice so that I don’t repeat the same code every time and so that I don’t have to explicitly write all the classes and slugs in indexOf ?

Sorry, but I’m new and managed to do this by looking around on stackoverflow.

code that I tried to shorten (not work):

I tried to shorten the code like this, but the active class is always added to .link_home even when I’m on other pages, and the same happens with link_dashboard when the /account slug is present in the url

document.addEventListener("DOMContentLoaded", function() {
  const links = document.querySelectorAll(".item_menu a");

  links.forEach(link => {
    if (window.location.href.indexOf(link.getAttribute("href")) > -1) {
      link.classList.add('active');
    }
  });
});

Original code (work):

<!-- Vertical Navigation -->
<div class="vertical_nav">

  <!-- User Menu -->
  <div class="user_menu">
    <div class="wrap_user_navigation">
      <div class="user_navigation">
        <div class="item_menu">
          <a class="link_dashboard" href="https://mywebsite.it/account">Dashboard</a>
        </div>

        <div class="item_menu">
          <a class="link_ordini" href="https://mywebsite.it/orders">I miei ordini</a>
        </div>

        <div class="item_menu">
          <a class="link_downloads" href="https://mywebsite.it/downloads">Libreria Downloads</a>
        </div>

        <div class="item_menu">
          <a class="link_settings" href="https://mywebsite.it/settings">Impostazioni</a>
        </div>
      </div>  
    </div>  
  </div>

  <div class="main_menu">
    <div class="item_menu">
      <a class="link_home" href="https://mywebsite.it/">Home</a>
    </div>  

    <div class="item_menu">
      <a class="link_expdocs" href="https://mywebsite.it/explore-docs">Explore Docs</a>
    </div> 

    <div class="item_menu">
      <a class="link_coaching" href="https://mywebsite.it/services">Online Coaching</a>
    </div> 

    <div class="item_menu">
      <a class="link_calculator" href="https://mywebsite.it/math">Fitness Calculator</a>
    </div> 
  </div>

  <!-- Docs Menu -->
  <div class="doc_menu">
    <div class="item_menu">
      <a class="link_anadocs" href="https://mywebsite.it/docs-anatomy">Docs Anatomy</a>
    </div> 

    <div class="item_menu">
      <a class="link_evidence" href="https://mywebsite.it/evidence-based">Evidence Based</a>
    </div> 

    <div class="item_menu">
      <a class="link_strengthvalue" href="https://mywebsite.it/strength-value">Strength Value</a>
    </div> 

    <div class="item_menu">
      <a class="link_mission" href="https://mywebsite.it/mission">Mission</a>
    </div> 
  </div>

  <!-- Footer Items -->
  <div class="footer_menu">
    <div class="item_menu">
      <a class="link_support" href="https://mywebsite.it/supporto">Supporto</a>
    </div> 

    <div class="item_menu">
      <a class="link_logout" href="https://mywebsite.it/wp-login.php?action=logout">Logout</a>
    </div> 
  </div>

</div>
document.addEventListener("DOMContentLoaded", function() {

  // Add - Remove class active for user_menu
  if(window.location.href.indexOf("account") > -1) {
    document.querySelector(".link_dashboard").classList.add('active');
  } 
  if(window.location.href.indexOf("orders") > -1) {
    document.querySelector(".link_ordini").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  }   
  if(window.location.href.indexOf("downloads") > -1) {
    document.querySelector(".link_downloads").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  } 
  if(window.location.href.indexOf("settings") > -1) {
    document.querySelector(".link_settings").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  } 

  // Add - Remove class active for main_menu
  if(window.location.href === "https://mywebsite.it/") {
    document.querySelector(".link_home").classList.add('active');
  }
  if(window.location.href.indexOf("explore-docs") > -1) {
    document.querySelector(".link_expdocs").classList.add('active');
  }   
  if(window.location.href.indexOf("services") > -1) {
    document.querySelector(".link_coaching").classList.add('active');
  } 
  if(window.location.href.indexOf("math") > -1) {
    document.querySelector(".link_calculator").classList.add('active');
  }

  // Add - Remove class active for doc_menu
  if(window.location.href.indexOf("docs-anatomy") > -1) {
    document.querySelector(".link_anadocs").classList.add('active');
  } 
  if(window.location.href.indexOf("evidence-based") > -1) {
    document.querySelector(".link_evidence").classList.add('active');
  }   
  if(window.location.href.indexOf("strength-value") > -1) {
    document.querySelector(".link_strengthvalue").classList.add('active');
  } 
  if(window.location.href.indexOf("mission") > -1) {
    document.querySelector(".link_mission").classList.add('active');
  }
});

How to use a fetched access token to fetch an endpoint?

How can I use (insert) a (just) fetched access token in Javascript to get access to an endpoint (access ID is to be added to the endpoint URI – oauth2 – Strava API).

I tried to add the fetched access token as const and var to the URI of the endpoint, but I do not get any data returned. All is working if I manually insert the actual access_code in the URI (FETCHED_ACCESS_TOKEN), but how do I pick it up to be used automatically in the endpoint URI?

JAVASCRIPT CODE I USED:

let _data = {
    client_id:"11111",
    client_secret:"AAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    code:"exchange_code",
    grant_type:"authorization_code"
}

fetch("https://www.strava.com/api/v3/oauth/token", {
  method: "POST",
  body: JSON.stringify(_data),
  headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json()) 
.then(json => console.log(json))
.then(json => {data = json})
.then(res => getActivities(res))
.catch(err => console.log(err));


const auth_link = "https://www.strava.com/oauth/token"

async function getActivities(res) {

    const activities_link = "https://www.strava.com/api/v3/segments/11111111?access_token=FETCHED_ACCESS_TOKEN"

                await fetch(activities_link)
                    .then(res => res.json())
                    .then(json => console.log(json));

            }