How to customize html source in ckeditor 5

I’m able to get the ckeditor to display the sourceEditing plugin correctly. What I’m trying to do is customize the ckeditor so when I upload an image instead of the image source being something like this:

<figure class="image image-style-side">
    <img src="https://c.cksource.com/a/1/img/docs/sample-image-bilingual-personality-disorder.jpg">
    <figcaption>
        One language, one person.
    </figcaption>
</figure>

I want it to display images of different size when depending on screen width like this:

<picture class="image image-style-side">
  <source media="(max-width: 799px)" https://small-c.cksource.com/a/1/img/docs/sample-image-bilingual-personality-disorder.jpg">
  <source media="(min-width: 800px)" https://medium-c.cksource.com/a/1/img/docs/sample-image-bilingual-personality-disorder.jpgg">
  <img src="elva-800w.jpg" alt="https://largmc-.cksource.com/a/1/img/docs/sample-image-bilingual-personality-disorder.jpgElva">
</picture>

Is something like this even possible?

I want to JSON Parse an array of objects inside an object – articles from the body, how can I do that?

I am making an api request in Alan studio and the news api returns an object from which I want to parse “articles” and store it and send them to my react code for displaying them on the news cards

But when I parse articles from the body, articles is becoming undefined.How can I JSON parse it?

Given below is the data returned from news api.

{
    "status": "ok",
    "totalResults": 10,
    "articles": [
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Monkeypox: Nigeria bans bushmeat to prevent virus spread",
            "description": "Experts say it is possible that the virus can be caught by eating meat from an infected animal.",
            "url": "http://www.bbc.co.uk/news/world-africa-61676841",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/983B/production/_125017983_gettyimages-453645236.jpg",
            "publishedAt": "2022-06-02T17:22:28.5473137Z",
            "content": "By Chris EwokorBBC News, AbujarnImage caption, Bushmeat is a delicacy in parts of Nigeria, but in other places it can be a vital source of foodrnThe Nigerian government has banned the sale of bushmea… [+2373 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Ukraine war: Zelensky says Russia controls a fifth of Ukrainian territory",
            "description": "Ukraine's president says Russia has taken 20% of Ukraine's territory, as the war nears its 100th day.",
            "url": "http://www.bbc.co.uk/news/world-europe-61675915",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/130F7/production/_125017087_hi076131363.jpg",
            "publishedAt": "2022-06-02T17:22:24.7575621Z",
            "content": "By Matt MurphyBBC NewsrnImage caption, A Russian soldier in MariupolrnUkraine's President Volodymyr Zelensky says that Russian forces have seized 20% of his country's territory, as Moscow's invasion … [+5338 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Oklahoma hospital shooting: Five dead after gunman targets physician",
            "description": "Police say the man blamed the doctor for his back pain and had purchased a rifle only hours earlier.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61676811",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/1307/production/_125017840_gettyimages-1241045718.jpg",
            "publishedAt": "2022-06-02T16:52:23.4616839Z",
            "content": "Image source, Getty ImagesrnImage caption, Police respond to the scene of Wednesday's shooting at St Francis HospitalrnPolice have said a gunman who killed three employees and a patient at an Oklahom… [+2376 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Canada says China 'buzzing' military flights in Asia",
            "description": "Canada called the incidents are unprofessional and potentially hazardous to aircrew in the Pacific.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61654043",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/75B3/production/_125013103_gettyimages-1341999649.jpg",
            "publishedAt": "2022-06-02T13:37:19.2266278Z",
            "content": "By Bernd Debusmann JrBBC News, WashingtonrnImage source, Getty ImagesrnImage caption, Chinese military aircraft at an airshow in September 2021rnCanadian military aircraft operating in Asia have been… [+2007 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Depp-Heard trial: Why Johnny Depp lost in the UK but won in the US",
            "description": "Experts say key factors included having a jury trial and his lawyers using a specific legal tactic.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61673676",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/6037/production/_125013642_gettyimages-1241024662.jpg",
            "publishedAt": "2022-06-02T12:22:23.3055092Z",
            "content": "By Robin Levinson-KingBBC NewsrnImage source, Getty ImagesrnIn 2020, Hollywood actor Johnny Depp lost a UK libel lawsuit against the Sun newspaper. But on Wednesday, he won a similar lawsuit against … [+2956 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Turkey wants be be called Türkiye in rebranding move",
            "description": "The country wants to be called Türkiye as part of a rebranding campaign launched by its president.",
            "url": "http://www.bbc.co.uk/news/world-europe-61671913",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/17CDD/production/_125010579_bluemosquegetty.jpg",
            "publishedAt": "2022-06-02T11:07:25.2572035Z",
            "content": "Image source, @MevlutCavusoglurnImage caption, Turkish Foreign Minister Mevlut CavusoglurnTurkey will be known as Türkiye at the United Nations from now on, after it agreed to a formal request from A… [+1736 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Texas school shooting victim's parents mourn 'best friend'",
            "description": "The parents of Alithia Ramirez say they want the world to remember their daughter through her art.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61669234",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/11FC6/production/_125007637_p0cbl2cx.jpg",
            "publishedAt": "2022-06-02T10:07:17.1192126Z",
            "content": "Last week 10-year-old Alithia Ramirez was shot and killed when a gunman opened fire at her primary school in Uvalde, Texas. rnHer parents say they want the world to remember their daughter was good a… [+168 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Bill Cosby 'pounced' on teen in Playboy Mansion",
            "description": "The comedian's lawyers dismiss the latest claim against him - stemming from 1975 - as a "fabrication".",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61664500",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/64DC/production/_125002852_gettyimages-1040552476.jpg",
            "publishedAt": "2022-06-02T07:37:18.1596491Z",
            "content": "Image source, Getty ImagesrnImage caption, Bill Cosby at his sentencing in Pennsylvania in 2018rnLess than a year after his sex assault conviction was thrown out and he walked free from prison, comed… [+2473 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Queen’s Platinum Jubilee: Trooping the Colour to begin celebrations",
            "description": "The Queen's Birthday Parade will kick off four days of celebrating the monarch's 70-year reign.",
            "url": "http://www.bbc.co.uk/news/live/uk-61516564",
            "urlToImage": "https://m.files.bbci.co.uk/modules/bbc-morph-news-waf-page-meta/5.2.0/bbc_news_logo.png",
            "publishedAt": "2022-06-02T06:07:24.9486456Z",
            "content": "Trooping the Colour is an annual military parade that marks the Queens official birthday - which this year falls on 11 June (her actual birthday is 21 April).rnThis is a centuries-old tradition which… [+973 chars]"
        },
        {
            "source": {
                "id": "bbc-news",
                "name": "BBC News"
            },
            "author": "BBC News",
            "title": "Depp-Heard trial: Jury sides mostly with Depp in defamation case",
            "description": "Jurors award Mr Depp $15m in compensatory and punitive damages, but also award Ms Heard $2m.",
            "url": "http://www.bbc.co.uk/news/world-us-canada-61668780",
            "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/12926/production/_125007067_tv076335814.jpg",
            "publishedAt": "2022-06-02T01:37:20.4013741Z",
            "content": "Media caption, Watch: Depp v Heard defamation case concludes in courtrnA US jury has found Amber Heard defamed ex-husband Johnny Depp with an article in which she claimed she was a victim of domestic… [+4697 chars]"
        }
    ]
}

// News by Source
intent('Give me the news from $(source* (.*))', (p) => {
    let NEWS_API_URL = `https://newsapi.org/v2/top-headlines`;
    
    if(p.source.value) {
        NEWS_API_URL = `${NEWS_API_URL}?sources=${p.source.value.toLowerCase().split(" ").join('-')}&apiKey=${API_KEY}`;
    }

    api.request(NEWS_API_URL, (error, response, body) => {
        const { articles } = JSON.parse(body);
        
        console.log(articles); // returns undefined
        
        if(articles?.length === 0) {
            p.play('Sorry, please try searching for news from a different source');
            return;
        }
        
        savedArticles = articles;
        
        p.play({ command: 'newHeadlines', articles });
        p.play(`Here are the (latest|recent) ${p.source.value}.`);
  
        p.play('Would you like me to read the headlines?');
        p.then(confirmation);
    });
})

How to hide a custom context menu when over a button or element

I am looking for a simple way to hide the custom context menu unless over a button or element. Here is a simple example I coded up containing a custom context menu and a button I wish to have it attached to. I am thinking maybe there could be an event listener that looks out for an on hover over the element, or maybe a function that toggles it on or off when needed? Also i was wondering if the button or element wasn’t defined with a class or ID is there still a way to know when you are over it maybe via coordinates (Not necessary just curious if possible)? The idea is there will be multiple elements that will require the context menu but the general space around the elements in the body should not show the custom menu.

function view() {

const contextMenu = document.getElementById('context-menu');
const scope = document.querySelector("body") ;

//body

var listLength = contextMenu.children.length;
for (i = 0; i < listLength; i++) contextMenu.removeChild(contextMenu.children[0]);


      contextMenuadd(contextMenu,"line 1 of context menu",1);
      contextMenuadd(contextMenu,"line 2 of context menu",2);
      contextMenuadd(contextMenu,"line 3 of context menu",3);
      contextMenuadd(contextMenu,"line 4 of context menu",4);

scope.addEventListener("contextmenu", (event) => {
event.preventDefault();

const { clientX: mouseX, clientY: mouseY } = event;

contextMenu.style.top = `${mouseY}px`;
contextMenu.style.left = `${mouseX}px`;
contextMenu.classList.add('visible');
contextMenu.style.display='block';
contextMenu.style.zIndex=20000;
contextMenu.style.position='fixed';
contextMenu.style.width="360px";
contextMenu.style.borderRadius="5px";


});

scope.addEventListener("click", (e) => {
  if (e.target.offsetParent != contextMenu) {
  contextMenu.style.display='none';
  }
});

};

document.addEventListener('DOMContentLoaded', view);    

function contextMenuadd(contextMenu, menustring,count ){
var action = function (e) {
    //menuLink;
    let currentRow = $(event.target)[0].parentElement ;
    var index = parseInt(currentRow.row );
    var value = currentRow.textContent ;
     en(href,'_self');
     
  };    


var menuitem = document.createElement('LI');
menuitem.addEventListener('click', action);
menuitem.classList.add("hotspot__item");
menuitem.innerHTML = '<a href="#">' + menustring + '</a>';
menuitem.row=count;


contextMenu.appendChild(menuitem);

};

document.addEventListener('click', function(e){
let inside = (e.target.closest('#container'));
if(!inside){
let contextMenu = document.getElementById('contextMenuId');
contextMenu.setAttribute('style', 'display:none');
}
}); 
#context-menu {
position: fixed;
z-index: 10000;
width: 180px;
background: #ffaaaa;
border-radius: 5px;
display: none;
}



#context-menu.item {
padding: 2px 4px;
font-size: 12px;
color: #eee;
cursor: pointer;
border-radius: inherit;
}
<html>

<body id="allofit">
<header>
    <h2>CGM View Example</h2>
</header>

<gm:figure-group>

<div id='sdi_canvas1' style="width:400px; height:400px">

<button id="container">  this is data in my DIV</button>

</div>
 <div id="context-menu" class="context-menu" 
oncontextmenu="ShowMenu('contextMenu',event)" style="display:none">
 <div class="item">Option 1</div>
 <div class="item">Option 2</div>
  </div>

</body>

</html>

Here’s a fiddle for reference.

JSFiddle

Cannot set properties of null (setting ‘textContent’)

I have recently started coding.

I wanted to make a site where typing effect is reproduced.

I followed a tutorial, but opening the Chrome console I find this error:
“Cannot set properties of null (setting ‘textContent’)”

If I try to run it on codepen it works, but if I use my text editor and run the code on Chrome it doesn’t.

I also leave you the link for the code:
https://codepen.io/andreab16/pen/KKQegQN

var texts = ["designer", "F1 enthusiast", "guy", "human"];

let count = 0;
let index = 0;
let currentText = "";
let letter = "";

(function type() {
  if (count === texts.length) {
    count = 0;
  }

  currentText = texts[count];

  letter = currentText.slice(0, ++index);

  document.querySelector(".typing").textContent = letter;
  console.log("ok");

  if (letter.length === currentText.length) {
    count++;
    index = 0;
  }

  setTimeout(type, 250);
})();

Thank you very much everyone

How can i get the difference values from an attribute? [duplicate]

I want to get all different values of the attribute title, i think i should be necesary to verify to all objects

for example

first object
     weight:1
     height:14
     title:"badaboom" 
second object
     weight:23
     height:24
     title:"heros"
third object
     weight:267
     height:43
     title:"badaboom"

the result should be “badaboom”, “heros”

its posible do that with firebase?

my idea it was:

const snapshot = await tokensRef.where('project', '==', project).get()
 snapshot.docs.map((doc) => doc.data())

and then filter with javascript, but that it will not be fast, i want to solve with firebase directly

pkg package does not include all files

I have node.js app. I installed pkg to create executive file that can be run on any platform. I use pkg . command for it. The problem is I have few csv files and config.json file where I store all of my settings. They are all in /settings/ folder. The problem is that they are not included in the pkg package and I get error after trying to run it. I tried to add

 "assets": [
      "settings/*",
      "settings/**/*"
    ]

into package.json file but it didn’t work. How can I add all files that are in the /settings/ folder so they are also included in the executive file without any errors?

Javascript ES6 spread transformation changing Promise return content in Nest JS auth example

I’m using some of the NestJS sample repo 19-auth-jwt to implement an authentication system. But I’m facing a bug.

In the provider for the auth module (auth.services.ts), the method validateUser() uses JS ES6 syntax to remove the password from the user before returning it, as explained in the docs.

  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.usersService.findOne(username);
    if (user && user.password === pass) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

This is not working for me, result looks like this:

{
  '$__': InternalCache {
    activePaths: StateMachine {
      paths: [Object],
      states: [Object],
      stateNames: [Array]
    },
    skipId: true,
    strictMode: true,
    selected: {},
    fields: {},
    exclude: null
  },
  '$isNew': false,
  _doc: {
    _id: new ObjectId("6299077a1c8989d6bdc3cb34"),
    first_name: 'Test',
    email: '[email protected]',
    password: '$2b$10$/ndkmG7qLh8RReko7TvsPOC15xd.mVDUY9mC3SVbkVndgZlVDzU4.',
    __v: 0
  }
}

Not only has it not removed the password but also it is creating a bizarre data structure which means I can’t get the user data which I then need to pass in my JWT without changing the code to access the _doc.

If I just return user instead it works (but obviously doesn’t remove the password.

My questions are:

  1. Why is this happening? My best guess is this is something to do with promises but don’t know.
  2. Should I be concerned about not removing the password if it is well protected? Note that I’m not actually returning it, this request only returns the JWT which holds the user _id, no more data.
  3. If it is a concern, what can I do about it?
  4. Is this a bug or my mistake?

I’m using MongoDB and mongoose as you might be able to tell. I’m new to Nest btw.

Reference to the code line where this is happening.

Thank you!

How to reset Cypress window.location.href after test

I am testing some ui that on click updates the window.location.href. I have two tests, the first one works, but the second starts in the location set by the ui in the previous test. This is wrong and stops test two from starting on the right page.

How can I reset the window.location.href or just the Cypress browser location in general back to where it was at the beginning of the first test?

I have checked the window.location.href at the start of the second test and it looks autogenerated and so I don’t think wise to try and hardcode that value into window.location.href at the start of the second test.

Looking for something I can run at afterEach.

Thank you.

RegEx to check that path is not page

I’m trying to write a regular expression to check that the pathname is a “page”, but so far without success.

Must match (include relative path, without domain name):

https://example.com/
https://example.com/about/
https://example.com/about/index.htm
https://example.com/about/index.html
https://example.com/contacts/index.php
https://example.com/search/search.php?sort=abc&q=pic.jpg
https://example.com/some-dir/some.dir/some_page123.html

Must not match:

https://example.com/file.pdf
https://example.com/directory/file.extesion
https://example.com/files/file.min.js
https://example.com/download/somefile.exe?hash=longlonghash&referrer=/cat/index.html

I need to replace ActionLink for Dropdownlist

I’m having a foreach that it gives me a list of values that when click it call a Controller.


  @foreach (var item in Model)
    {
        <div>@Html.ActionLink(item.Text, "UpdateController", new { subSectionID = item.Value, subsectionName = item.Text })</div>

    }

I would like to do this but now using a dropdown list where clicking on the value redirects me to the controller.

If someone knows how to do it or do it in some other way, maybe using Select in html, it would help me, thanks!

Why do my buttons not get the eventlisteners i set?

I am making a digital shop and want to add eventlisteners to delete items from my cart. I am using firebase for my project. When I press my buttons, nothing happens because there is no eventListener attached to the button for some reason. In the picture (if it works) there is no “click” eventListener. How can I fix the eventListener?

function getCart() {
db.collection("user").where("uid", "==", auth.currentUser.uid).get().then((snapshot) =>{
dokumenter = snapshot.docs;
dokument = dokumenter[0].data();

cartHTML.innerHTML = ""

cartHTML.innerHTML += "<div id='cartHeader'>"+dokument.firstNamee +"'s cart</div>"



console.log(dokument.Cart);
if (dokument.Cart == 0) {
  cartHTML.innerHTML = "<div id='emptyCart'>Cart is empty</div>"
} else {

for (let i = 0; i < dokument.Cart.length; i++) {
  carAmount = dokument.Cart[i].amount;
  carModel = dokument.Cart[i].id;

 

  let cartDIV = document.createElement("div");
  cartDIV.setAttribute("class", "cartDIV");
  cartDIV.setAttribute("id", "cart"+dokument.Cart[i].id);


  let deleteFromCartBTN = document.createElement("button");
  deleteFromCartBTN.setAttribute("class", "deleteBTN");
  deleteFromCartBTN.setAttribute("data-id", dokument.Cart[i].id);
  // deleteFromCartBTN.setAttribute("id", "delete"+dokument.Cart[i].id)
  deleteFromCartBTN.innerHTML = "Slett fra handlekurv"

  let minus = document.createElement("button");
  minus.setAttribute("class", "minusCart");
  minus.setAttribute("data-id", dokument.Cart[i].id);
  minus.innerHTML = "-";
  minus.addEventListener("click", minusCart)

  let pluss = document.createElement("button");
  pluss.setAttribute("class", "plussCart");
  pluss.setAttribute("data-id", dokument.Cart[i].id);
  pluss.innerHTML = "+";
  pluss.addEventListener("click", plussCart)

  let modelDIV = document.createElement("div");
  modelDIV.setAttribute("class", "modelDIV");
  modelDIV.innerHTML = "Model:" + " " + dokument.Cart[i].id;

  let amountDIV = document.createElement("div");
  amountDIV.setAttribute("class", "amountDIV");
  amountDIV.innerHTML = "Amount:" + " " +dokument.Cart[i].amount;

  console.log();
  cartDIV.appendChild(pluss)
  cartDIV.appendChild(minus)
  cartDIV.appendChild(modelDIV);
  cartDIV.appendChild(deleteFromCartBTN);
  cartDIV.appendChild(amountDIV);
  cartHTML.appendChild(cartDIV);
  
  deleteFromCartBTN.addEventListener("click", deleteItemCart)
}
}

})
}

Get a specific list item with SPFX and PNP/JS and show it in SharePoint Online Webpart/Widget

I want to read the values of a specific list element by ID and show it on a SharePoint site.

The problem is that I tried to use the PNP Framework, but some of the components are not working any longer.
Here is my code so far.
I hope you can help me.

import * as React from 'react';
import styles from './Webpartprojectsw.module.scss';
import { IWebpartprojectswProps } from './IWebpartprojectswProps';
import { escape } from '@microsoft/sp-lodash-subset';
import * as jquery from 'jquery';
import { IItemAddResult, DateTimeFieldFormatType } from "@pnp/sp/presets/all";
import { spfi, SPFI, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
 import "@pnp/sp/lists";
import "@pnp/sp/items";

export interface ISolypProjectListItemsState{
    Title: string,
    ID: number,
    StartDate: string,
    EndDate:string,
    ProjectPhase: string,
    TrafficLight:string,
    message: string
  }

  export default class Webpartprojectsw extends     

 React.Component<IWebpartprojectswProps,ISolypProjectListItemsState> {

public static siteurl: string="";
public constructor(props:IWebpartprojectswProps, state: ISolypProjectListItemsState){
   super(props);
   this.state={
         Title:"",
         ID:0,
        StartDate:"",
        EndDate:"",
        ProjectPhase:"",
        TrafficLight:"",
        message:""
   };
   Webpartprojectsw.siteurl= this.props.websiteurl;
 }

 public componentDidMount()  {

    this._ReadItem();
 }



 public render(): React.ReactElement<IWebpartprojectswProps> {


  return (
   <div>
    {this.state.message}
    {this.state.Title}
   </div>      
      
  );
}
 private async _ReadItem(){
 // get a specific item by id
const item: any = await sp.web.lists.getByTitle("ProjectStatusList").items.getById(1).get();
console.log(item);
 this.setState({message:"Last Item Created Title:--> " + item.Title + item.TrafficLight});

  }
  }

Thank you very much!

Matthias

How to generate HTML table with JavaScript an array of objects?

I’ve an array of objects and I want to convert it into a visual table in HTML; So I did it last night But I was tired, I don’t think it is the right way of doing it, even though it’s working and give the expected result!

let notes = [
  { note: "n1", subject: "subject1", value: 10 },
  { note: "n2", subject: "subject2", value: 15 },
  { note: "n2", subject: "subject2", value: 5 },
  { note: "n3", subject: "subject2", value: 20 },
];

function make_matrix(objs) {
  let rows = [...new Set(objs.map(({ subject }) => subject))];
  let columns = [...new Set(objs.map(({ note }) => note))];
  let array_objs = {};
  for (const obj of objs) {
    let { note, subject, value } = obj;
    if (array_objs[subject + "-" + note])
      array_objs[subject + "-" + note] = [
        ...array_objs[subject + "-" + note],
        obj,
      ];
    else array_objs[subject + "-" + note] = [obj];
  }
  for (const [k, v] of Object.entries(array_objs)) {
    total = v.map(({ value }) => +value).reduce((a, b) => a + b);
    array_objs[k] = total;
  }
  let od = {};
  for (const [k, v] of Object.entries(array_objs)) {
    const [key, value] = k.split("-");
    if (od[key]) {
      od[key] = [...od[key], { [value]: v }];
    } else {
      od[key] = [{ [value]: v }];
    }
  }
  let trs = "";
  for (const [key, value] of Object.entries(od)) {
    trs += "<tr><th>" + key + "</th>";
    for (const col of columns) {
      const entry = value
        .map((x) => Object.entries(x)[0])
        .find((x) => x[0] == col);
      if (
        value
          .map((x) => Object.entries(x)[0])
          .map((x) => x[0])
          .includes(col)
      ) {
        trs += "<td>" + entry[1] + "</td>";
      } else {
        trs += "<td>0</td>";
      }
    }
    trs += "</tr>";
  }
  let table = `<table>
                <tr><th>Subjects</th><th>${columns.join(
                  "</th><th>"
                )}</th></tr>
              ${trs}
                </table>`;
  return table;
}
document.querySelector(".content").innerHTML = make_matrix(notes);
table {
  border-collapse: collapse;
  border: 1px solid;
}
tr,
th,
td {
  border: 1px solid;
  padding: 3px 10px;
}
<div class="content"></div>

Could you please check the code, and give any feedback is much appreciated!

Why does my exit button not exit the game but cancel button works?

I have an exit button for a game which should close when “exit” is clicked and cancel the prompt when “cancel” is clicked:

const exitPrompt = document.getElementById('exit-prompt');
const exitBtn = document.getElementById('exit-btn');
const exitCancelBtn = document.getElementById('exit-cancel-btn');

exitBtn.addEventListener('click', () => {
  //window.location.assign('../');
  window.location.assign('/pages/games');
});

exitCancelBtn.addEventListener('click', () => {
  showExitPrompt();
});
    
exitPrompt.addEventListener('click', () => {
  //window.location.assign('../');
  window.location.assign('/pages/games');
});

Is there a reason why the cancel button closes the pop-up but the exit button doesn’t go to /pages/games?