Javascript function not returning value when working with blazor and JSInterop

I am trying to run javascript code through C#. I am using JSInterop to call javascript function from C#. I have installed metammask sdk and then trying to get the account after connecting.

window.getAccount = async function () {
    try {
        const accounts = await provider.request({ method: "eth_requestAccounts" });
        console.log("accounts = ", accounts);
        if (accounts.length != 0 || accounts != undefined) { 
            console.log("accounts = ", accounts);
            console.log("account[0] = ", accounts[0]);
            return accounts[0]; // Return the first account
        }
        else
            return "new error"
    } catch (err) {
        if (err.code === 4001) {
            console.log("Please connect to MetaMask.");
            return "Allow to connect to Metamask"; // Return a message indicating to connect to MetaMask
        } else {
            console.error(err);
            throw err; // Re-throw the error
            return " error ..."
        }
    }
}

The above is my javascript code. Here i am returning the account if the user accepts the connecting request and returning a message if he rejects.

I am calling this function from the cs file like

        string output = await JsRuntime.InvokeAsync<string>("getAccount");

        Console.WriteLine("output = ",  output);

The issue:

  1. When I am rejecting the connection request the message “Please connect to metamask” gets consoled but after that an error occurs : crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
    Unhandled exception rendering component: Cannot read properties of undefined (reading ‘0’)
    TypeError: Cannot read properties of undefined (reading ‘0’)
    at window.getAccount (https://localhost:57476/js/index.bundle.js:1:483)
    Microsoft.JSInterop.JSException: Cannot read properties of undefined (reading ‘0’)
    TypeError: Cannot read properties of undefined (reading ‘0’)
    at window.getAccount (https://localhost:57476/js/index.bundle.js:1:483)
    at Microsoft.JSInterop.JSRuntime.d__16`1[[System.String, System.Private.CoreLib,

stating that I am trying to access the 0 index of an undefined object (most probably accounts).

  1. When I am accepting the request then nothing/empty string is returned.

I tried changing the structure of the getAccount funtion hoping the return statement miht work, but no progress.

Expected result: The account should be returned if the user accepts the connect request and if the user rejects the connect the error message should be returned.

How do i get rid of this “qlState: ‘22007’, sqlMessage: “Incorrect date value: ‘undefined’ for column ‘issue_date’ at row 1”

I am working on a DBMS project – “Hostel Management System”. And the issue is that:
On the student page, one of the facilities given to them is to complaint file. Now the data that they enter is to be sent to the backend.

first see the the complaint page:
SS of entering the details
[![after submitting, check the inspect bar.]see the inspect bar.

as u can see i get this response:

Response {type: 'opaque', url: '', redirected: false, status: 0, ok: false, …}
body
: 
(...)
bodyUsed
: 
false
headers
: 
Headers {}
ok
: 
false
redirected
: 
false
status
: 
0
statusText
: 
""
type
: 
"opaque"
url
: 
""

the data is not getting added to the database.
i got this error:

  code: 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD',
  errno: 1366,
  sql: 'n' +
    '    INSERT INTO complaint(compType,hos_id,issue,issue_date)n' +
    '    VALUESn' +
    '    (n' +
    "        'undefined',n" +
    "        'NaN',n" +
    "        'undefined',n" +
    "        'undefined'n" +
    '    );n' +
    '    ',
  sqlState: 'HY000',
  sqlMessage: "Incorrect integer value: 'NaN' for column 'hos_id' at row 1"
}

I tried the following:

1.
This is under the file comp.js –

// Function to handle form submission
async function submitComplaint(event) {
  event.preventDefault();

  // Get form data
  var complaintType = document.getElementById('complaintType').value;
  var hostelID = document.getElementById('hostelID').value;
  var issueDescription = document.getElementById('issueDescription').value;
  var issueDate = document.getElementById('issueDate').value;
  console.log(typeof hostelID); // Check the type of hostelID

// Validate hostelID as an integer
if (!Number.isInteger(Number(hostelID))) {
  alert("Hostel ID must be a valid integer.");
  return; // Stop further execution
}
  // Create a data object to send to the backend
  const complaintData = {
    compType: complaintType,
    hos_id: hostelID,
    issue: issueDescription,
    issue_date: issueDate
  };

  console.log(complaintData);


  try {
    const response = await fetch('http://localhost:3000/posts/complaint', {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(complaintData)
    });
  
    console.log(response); // Log response from the backend
  
  } catch (error) {
    console.error('Error:', error);
  }
  1. i made sure that hostel id is integer only. i changed the type of hostelID to number in html:
    <label for="hostelID">Hostel ID:</label>
    <input type="number" id="hostelID" name="hostelID"><br>
  1. I used the parseInt in postControllers.js:
exports.createNewCompaint = async (req, res, next) => {
  console.log(req);
  try {
    let { compType,hos_id,issue,issue_date } = req.body;
    // Convert hos_id to an integer
    hos_id = parseInt(hos_id);
    let postComplaint = new PostComplaint(compType,hos_id,issue,issue_date);
    res.send("Complaint Registered");

    postComplaint = await postComplaint.save();
    res.status(201).json({ message: "Success" });
    console.log(postComplaint);
  } catch (error) {
    console.log(error);
    next(error);
  }
};

in the database:

create table try.complaint(
compType VARCHAR(100),
hos_id INT,
issue VARCHAR(500),
issue_date date
);
describe complaint;

output

i have made sure that the connection is established between backend and mysql. the server was running.

i also tried changing the datatype of hos_id to varchar. but nothing changed. still getting the error. help.

how can i change error message in this code with function setCustomValidity? [closed]

class Validation {
 constructor(elements) {
        this.elements = null;
        this.form = null;
        if (typeof elements === 'string') {
            this.elements = document.querySelector(elements).querySelectorAll('input, select, textarea');
        } else if (typeof elements === 'object') {
            this.elements = elements;
        } else {
            throw new error('Error');
        }
        this.virtualForm();
    }
    virtualForm() {
        this.form = document.createElement("form");
        for (let i =0; i < this.elements.length; i++){
            this.form.appendChild(this.elements[i])
        }
        console.log(this.form)
    }

    validate() {
        console.log(this.form.checkValidity());
        console.log(this.form.reportValidity());
    }
}

i need to add setCustomValidity at this code i try to do this but no one is working, please help me somebody

Electron Share Audio & Desktop screen

I created a sharing screen and audio app, and everything is working fine but for many users, there is always missing sound either desktop sound or microphone while no errors

I tried to get the specific audio device for the microphone as the exact ID but it’s still the same, with the exact-ID I have to listen for audio source changes, and when changes occur and successfully changes the sender audio the audio is gone

const createStream = async () => {
    try {
      const stream = await (navigator.mediaDevices as any).getUserMedia({
        audio: {
          // echoCancellation: true,
          // noiseSuppression: true,
          // sampleRate: 44100,
          autoGainControl: false,
          echoCancellation: false,
          googAutoGainControl: false,
          noiseSuppression: false,
          volume: 1,
          // channelCount: 2,
          // deviceId: { exact: id },
        },
        video: false,
      });
      const stream1 = await (navigator.mediaDevices as any).getUserMedia({
        audio: {
          mandatory: {
            chromeMediaSource: 'desktop',
          },
        },

        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
          },
        },
      });

      const combineStreams = new MediaStream([
        ...stream.getTracks(),
        ...stream1.getTracks(),
      ]);

      return combineStreams;
    } catch (e: any) {
      // handle errors
    }
  };

  const handelPeer = async (peerId: string, user_type: string) => {
   // ... create peer connection
   peer.on('open', () => {
      connection.on('open', async () => { 
           dataSream.current = await createStream();
        callRef.current = peer.call(peerId, dataSream.current);
       }
    });
  }

Why is Next.js not fetching client-side data after TypeScript validation and posting to the backend?

i am a beginner and facing an issue with fetching data from MongoDB in Next.js. The client side is functioning properly and I have checked the console logs and schema validation. Additionally, I have used Zod validation

import { NextResponse } from "next/server";
import { MongoClient, MongoClientOptions } from "mongodb";
import { Request } from "express";
import express from "express";

const app = express();
app.use(express.json());

interface CustomMongoClientOptions extends MongoClientOptions {
 useUnifiedTopology?: boolean;
}

export async function POST(req: Request): Promise<NextResponse> {
 // Explicitly type req and return type
 if (req.method === "POST") {
   try {
     console.log("Received data:", req.body);
     const {
       first_name = "",
       last_name = "",
       email = "",
       job_title = "",
       company_name = "",
       website_name = "",
       help = "Learn More",
       services = "Local business SEO",
       info = "",
     } = req.body; // Access req.body directly without await
     console.log("firstname", first_name);

     const uri: string = process.env.MONGODB_URI || ""; // Use environment variable for URI

     const client = new MongoClient(uri, {
       useUnifiedTopology: true,
       useNewUrlParser: true,
     } as CustomMongoClientOptions);

     await client.connect();
     const collection = client.db("codeseo").collection("userdata");
     const doc = {
       first_name,
       last_name,
       email,
       job_title,
       company_name,
       website_name,
       help,
       services,
       info,
     };
     await collection.insertOne(doc);

     await client.close();

     return NextResponse.json("Data has been saved to MongoDB");
   } catch (error) {
     console.error("Error saving data to MongoDB:", error);
     return NextResponse.json("Data has not been saved");
   }
 } else {
   return NextResponse.json("Method not allowed");
 }
}

“I tried to use ChatGPT and received help, but the data is not being stored in my database. When I use req.body console log, it returns null. I searched for solutions online and found many tutorials on YouTube, but they all use Mongoose, which I don’t want to use. If anyone can help, please let me know. I can also provide the client-side code if needed. I used a letter for my environment, so I hid the URI that I wrote.

Full stack e-store development (MERN stack)

When running my server file called server.js using node, my ejs main page displays all my elements as a hyperlink, how do I fix this??
The main page is supposed to display products as well as its data in a grid row of 2, it does that fine but the product is displayed as a hyperlink and I did not code it into my textfile

Get the user’s location

I need to get the location of the user in php or javascript in wIn a web project, I need to get the location of the user, but due to sanctions, this is difficult for me, and I need help.eb application.
But because I’m in Iran, I’m banned and I can’t use the google map api or the following code

        navigator.geolocation.getCurrentPosition(function(location) {
            latitud = location.coords.latitude;
            longitude = location.coords.longitude;
            console.log(location.coords.latitude);
            console.log(location.coords.longitude);
            console.log(location.coords.accuracy);
        });

What can I do to get the user’s location?

This project of mine is developed on the Laravel platform and JavaScript is used for the frontend

In a web project, I need to get the location of the user, but due to sanctions, this is difficult for me, and I need help.

AssertionError: expected +0 to be 3; vi.spyOn()

In attempting to record the number of mock calls of Math.floor() within the function set_rgb_color, the following error is raised:

AssertionError: expected +0 to be 3 // Object.is equality

- Expected
+ Received

- 3
+ 0

Within the test, I’m expecting the mocked function to be called 3 times yet it’s returning 0.

test.utils.js

import { vi } from "vitest";

import { set_rgb_color } from './utils.js';

test("Verify that set_rgb_color returns a string representing a rgb color", () => {
     const mock_math_floor = vi.spyOn(Math, "floor");
     mock_math_floor.mockReturnValueOnce(210);
     mock_math_floor.mockReturnValueOnce(55);
     mock_math_floor.mockReturnValueOnce(111);
     const rgb_color = set_rgb_color();
     expect(mock_math_floor.mock.calls.length).toBe(3);
     expect(rgb_color).toBe(`rgb(210, 55, 11)`)
});

utils.js

function set_rgb_color() {
    return `rgb(${new Array(3).map(
        () => Math.floor(Math.random() * 256)
    ).join(",")})`;
}

export { set_rgb_color };

Changing the color of a text using Flask-Socketio in multiplayer

There is a button and whenever you click on it, it is supposed to toggle the color of the text below. It should also work in multiplayer, i.e: If u change the color, and if the other person also clicks on the button, it should change the color of the text back to the original color.
I have a basic idea on how I would do this:

  1. Have a button and a text with the class colored or uncolored.
  2. Whenever a person clicks on the it emits a socketio event to the server side.
  3. When the server receives the event from the server side, it broadcasts another event to all the people connected to the server.
  4. When the client recieves the event, it checks if the class of the text is colored or not and changes accordingly using if else statements.

    It should be working but it doesn’t work and takes a lot of time to load the webpage

Code:

main.py

from flask import Flask, render_template, url_for
from flask_socketio import emit, SocketIO

app = Flask(__name__)
app.config["SECRET_KEY"] = "secret_key"
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template("index.html")

@socketio.on("changeColorClient")
def changeColorServer(data):
    emit("changeColorServer", {"message" : "changed color"}, broadcast=True)
    print(data["message"])

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, use_reloader=True, log_output=True, debug=True)

style.css -> basically .colored: {some color of the text} and .uncolored: {some color of the text}
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>Color changer multiplayer</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
</head>
<body>
    <button id="button" onClick="changeColorClient()" class="uncolored">Click me to change the color of the text below</button>
    <h4 id="text">When you click the button above me you'll be able to change the color of my text.<br>This is can work in multiplayer.</h4>
</body>
<script type="text/javascript">
    var socketio = io();

    function changeColorClient () {
        socketio.emit("changeColorClient", {message: "changed color"})
    };

    socketio.on("changeColorServer", (message) => {
        text = document.getElementById("text");
        if (text.className == "uncolored") {
            text.className = "colored";
        } else {
            text.className = "uncolored";
        };
        console.log(message)
    });
</script>
</html>

JS class field setting is not saved in Cypress test

I create some test data as JS class in Cypress spec file. The instance of this class is used by the spec tests. Some fields of the class object are set in constructor and some are dynamically assigned. All the fields are private and I use getters and setters for getting/setting their values. The problem is that the fields set by constructor at the moment of creating the object remain unchanged accross the spec tests, but those that were set dynamically with setters in a certain test don’t save the assigned value in another tests. I guess it happens due to cross domain tests nature. Is there any way to keep the state of the field after its value was set?

Video file uploading by XMLHttpRequest failed on specific Android mobile

Our tester failed to upload video file(.mp4) on specific android mobile phone, but he could upload same file on iPhone and another android mobile phone.

Then I tried to test with him by connecting the android mobile phone to PC by USB to debug on chrome developer tools. But I couldn’t find any errors so far.

And I tried this changing php.ini like below URL:
xmlhttprequest file upload not working on mobile
It was not work for me.

Does anyone have some idea to solve this situation?

Thanks in advance.

— Server
-CentOS Linux 7
-nginx 1.20.1

— Frontend
-Javascript

— Backend
-PHP 7.3
-cakephp 3.8

— Devices / Success
-PC(Windows 10 Pro)
-Android 6.0.1
-Android 8.0.0
-iOS 16.2

— Devices / Failed
-Android 11
-Android 13

php.ini

memory_limit => 2G
upload_max_filesize => 2G
max_input_vars => 1000 
max_execution_time => 0
; post_max_size = 8M -- before changed
post_max_size = 64M

Javascript

var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('upfile', upfile); // upfile is uploading video file *1

xhr.onreadystatechange = function() {
    if( (xhr.status == 200 || xhr.status == 304) && xhr.response) {
        var data = xhr.response;

        console.log( 'COMPLETE! :' );
        console.log( data );
    } else {
        console.log( 'Failed. HttpStatus: '+xhr.status );
    }
};

xhr.open('POST', '/api/video/upload', true);
xhr.responseType = 'json';

xhr.send(fd);

**Javascript Log *1 **

# upfile
lastModified: 1713564962045
lastModifiedDate: Sat Apr 20 2024 07:16:02 GMT+0900 (日本標準時)
[[Prototype]]: Object
name: "VID_2024-04-20-07-15-56-811.mp4"
size: 10950674
type: "video/mp4"
webkitRelativePath: ""

cakePHP3.8

//srcControllerApiVideosController.php

public function upload(){

    // this $_FILES has no data on faled request. 
    $this->appInfoLog("api.videos.upload",
        ["request"=>$this->request,
            "_FILES"=>$_FILES,
        ]
    );
    
    // uploading procedure...
 }

cakePHP Log
On Success

2024-04-20 05:53:13 Info: {"request":{"trustProxy":true},"_FILES":{"upfile":{"name":"VID_20240419_155656.mp4","type":"video/mp4","tmp_name":"/tmp/phpAu0ege","error":0,"size":7330740}},"action":"api.videos.upload"}

On Failed

2024-04-20 06:31:52 Info: {"request":{"trustProxy":true},"_FILES":[],"action":"api.videos.upload"}

Then I tried to test with him by connecting the android mobile phone to PC by USB to debug on chrome developer tools. But I couldn’t find any errors so far.

discord bot js MessageComponent complete

have anyway to make the awaitMessageComponent complete without reply?

this is my code it work fine but have more way better?

const SelectResponse = await interaction.channel.awaitMessageComponent({
    filter: (i) => i.user.id === interaction.user.id && i.customId == "keyinfo"+keycodegen ,
    time: 30000,
});
SelectResponse.deferReply({ephemeral: true});
SelectResponse.deleteReply();

i need to do bot discord js

Container grid size with Flexbox and (media query) Javascript

I do Etch-a-Sketch – https://www.theodinproject.com/lessons/foundations-etch-a-sketch . But I want do something more than the assignment.

I need do this ONLY with Flexbox and JavaScript (without CSS Grid)

  1. When I do gridContainer.style.height = “100vh” , it is a little bit more than screen height. So I do 97vh. Is there another solution?

  2. I want add width=100vw (replace height = “97vh”) ONLY for mobile screen. But I cannot do this with media query javasript. (The result is grid container height more than width.) Maybe I don’t know something? How can I do this?

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="./styles.css" />
    <script src="./script.js" defer></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Etch-a-Sketch</title>
</head>

<body>

<div id="gridUser">

    <h1>Etch-a-Sketch</h1>

    <form id="gridForm">

        <p><label for="gridInput">Enter a number of squares per side: 1...100</label></p>
        <p><input id="gridInput" type="text"></p>

        <p><legend>Choose mouse hover color</legend></p>
        <p>

            <input id="gridRadioYellow" name="gridRadio" value ="yellow" type="radio" checked>
            <label for="gridRadioYellow"> Yellow</label>

            <input id="gridRadioRandomize" name="gridRadio" value ="randomize" type="radio">
            <label for="gridRadioRandomize"> Randomize</label>

            <input id="gridRadioRandomizeEverySquare" name="gridRadio" value ="randomizeEverySquare" type="radio">
            <label for="gridRadioRandomizeEverySquare"> Randomize every square</label>

        </p>

        <p><button type="submit">Submit</button></p>

    </form>

    <div id="gridText"></div><br/>

</div>

<div id="gridContainer"></div>

</body>
</html>
* {
    box-sizing: border-box;
    font-family: Arial, sans-serif;
    text-align: center;
}

body {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
}

#gridUser, #gridContainer {
    flex: 1 1 0%;
}

#gridInput {
    text-align: left;
}
// also add functional for yellow color (not randomize) and for randomize every square

let gridContainer = document.querySelector("#gridContainer");
let gridSize = 16*16;
let gridSquares = "";
let mouseSquares = [];
let mouseHoveringColor = "";

getGridPerSide();

function getGridPerSide() {

    let gridForm = document.querySelector("#gridForm");

    gridForm.addEventListener("submit", (e) => {
        e.preventDefault();

        let gridInput = document.querySelector("#gridInput");
        let gridRadio = document.querySelectorAll(`input[name="gridRadio"]`);
        let gridRadioChecked = "";
        let gridText = document.querySelector("#gridText");

        mouseHoveringColor = "";

        for (const gridRadioOne of gridRadio) {
            if (gridRadioOne.checked) {
                gridRadioChecked = gridRadioOne.value;
                break;
            } 
        }

        if (isNaN(gridInput.value) || gridInput.value < 1 || gridInput.value > 100) {
            gridText.innerHTML = `Enter a <em>right</em> number <strong>from 1 to 100</strong>`;
        } else if (gridRadioChecked === "yellow") {
            gridText.innerHTML = `
                The grid has <em>${gridInput.value}*${gridInput.value}</em> squares<br/>
                The mouse hover color is <strong>yellow</strong><br/>
            `;
            mouseHoveringColor = "yellow"; // value for doMouseHovering()
        } else if (gridRadioChecked === "randomize") {
            gridText.innerHTML = `
                The grid has <em>${gridInput.value}*${gridInput.value}</em> squares<br/>
                The mouse hover color is <strong>randomize</strong><br/>
            `;
            mouseHoveringColor = "randomize"; // value for doMouseHovering()
        } else {
            gridText.innerHTML = `
                The grid has <em>${gridInput.value}*${gridInput.value}</em> squares<br/>
                The mouse hover color is <strong>randomize every square</strong><br/>
            `;
            mouseHoveringColor = "randomizeEverySquare"; // value for doMouseHovering()
        }

        gridSize = gridInput.value * gridInput.value;

        createGrid();

    });
}

function createGrid() {

    gridContainer.innerHTML = ""; // grid clean for new submit

    for (let i=0; i < (gridSize); i++) {

        gridSquares = document.createElement("div");
        gridSquares.classList.add("gridSquares");
        gridContainer.appendChild(gridSquares);

        gridSquares.style.cssText = `
            width: calc(100% / ${gridInput.value});
            height: calc(100% / ${gridInput.value});
            background-color: #eee;
            border: 1px solid #ccc;
        `;

        gridContainer.style.cssText = `
            height: 97vh;
            width: auto;
            display: flex;
            flex-wrap: wrap;
            aspect-ratio: 1/1;
        `;

        mouseSquares.push(gridSquares); // create array for doMouseHovering()

    }

    doMouseHovering();

}

function doMouseHovering() {

// need mouseBackgroundColor for calculate "randomize" (NOT for "randomizeEverySquare")

    let mouseBackgroundColor = "";

    if (mouseHoveringColor === "yellow") {
        mouseBackgroundColor = "yellow";
    } else if (mouseHoveringColor === "randomize") {
        let r = Math.floor(Math.random() * 256);
        let g = Math.floor(Math.random() * 256);
        let b = Math.floor(Math.random() * 256);
        mouseBackgroundColor = `rgb(${r}, ${g}, ${b})`;
    }

    mouseSquares.forEach(gridSquares => {

        gridSquares.addEventListener('mouseover', () => {
            if (mouseHoveringColor === "yellow") {
                gridSquares.style.backgroundColor = mouseBackgroundColor;   
            } else if (mouseHoveringColor === "randomize") {
                gridSquares.style.backgroundColor = mouseBackgroundColor;
            } else {
                let r = Math.floor(Math.random() * 256);
                let g = Math.floor(Math.random() * 256);
                let b = Math.floor(Math.random() * 256);
                gridSquares.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
            }

        });

    });

}

I tried do this with CSS media query and JavaScript media query. The result is grid container height more than width. But the grid container must be square.

How can I filter an array, using a nested value?

I got an array with objects

"times": [{
  "id" : "id",
    "name" : "place",
    "location" : "place",
    "hours" : [
    {"day": "Sunday", "day_id": 0,
  "tags": "" },
    {"day": "Monday", "day_id": 1,
"tags": "" },
    {"day": "Tuesday", "day_id": 2,
"tags": "" },
    {"day": "Wednesday", "day_id": 3,
"tags": "" },
    {"day": "Thursday", "day_id": 4,
"tags": "" },
    {"day": "Friday", "day_id": 5,
"tags": "" },
    {"day": "Saturday", "day_id": 6,
"tags": "" }
    ]
    }
    ]

I am trying to filter into the Hours array within the object.

I am trying to find the objects that contains a specific day_id within the hours array.

I tried

let f1 = times.filter((item: { id: string; hours: { day_id : number;};}) => item.hours.day_id == 0 );

That did not work. What am I doing wrong here ?