Home > Back-end >  Unable to access key value pairs in js object
Unable to access key value pairs in js object

Time:08-09

Unable to access key value pairs in js object I'm trying to access current day from dayName but I'm unable to do so. it is showing undefined when I'm trying to access the dayName via dayNum key=.

JS

app.get("/", (req, res) => {

    
    
let dayName = {
    "1" : "Monday",
    "2" : "Tuesday",
    "3" : "Wednesday",
    "4" : "Thursday",
    "5" : "Friday",
    "6" : "Saturday",
    "0" : "Sunday"
}



   

     let today = new Date();
    
        let dayNum = today.getDay().toString();
        console.log(dayName.dayNum)
        res.render("list", {
            day : dayName.dayNum
        })

})

EJS

<!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>To Do List</title>
</head>

<body>
    <h1>Today is <%= day %>
    </h1>
</body>

</html>

OUTPUT:

enter image description here

enter image description here

CodePudding user response:

You should use the square bracket notation

res.render("list", {
    day : dayName[dayNum]
});

Also I would recommend using an array instead of object for dayName

const dayName = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

CodePudding user response:

app.get("/", (req, res) => {



let dayName = {
"1" : "Monday",
"2" : "Tuesday",
"3" : "Wednesday",
"4" : "Thursday",
"5" : "Friday",
"6" : "Saturday",
"0" : "Sunday"
}

 let today = new Date();

    let dayNum = today.getDay().toString();
    console.log(dayName[dayNum])
    res.render("list", {
        day : dayName[dayNum]
    })

})
  • Related