简体   繁体   中英

Problem getting a key value inside an object

I have a problem with this piece of code:

var Etudiants = {
"N13213316" : {
    "name" : "Touati Mohammed",
    "birthDate" : "05 June 2001",
    "age" : (Math.round((new Date().getTime() - new Date(this.Etudiants.N13213316[birthDate]).getTime()) / 1000 / 60 / 60 / 24 / 365.25)),
    "isStudent" : true,
    "departement" : {
            "2021" : "USMBA ENCG Fes",
            "2021" : "USMBA FLDM Fes"
    }
}
}

when i save it i get the following error code:

Uncaught ReferenceError: birthDate is not defined

So basically i'm training to get the value "05 June 2001" to pass it as an argument to the Date function, but i can't do so, however i can access the value from the browser console, where i did make the mistake exactly and thanks in advance.

There are three ways of how you can access object properties in JavaScript:

  1. With a dot:

    object.property

  2. With square brackets:

    object['property']

  3. With destructing:

    const { property } = object

So, basically, you mixed up two of these ways to access object property.

PS Do not access the field within the object literal as @roperzh mentioned.

The birthDate bit in the following expression:

this.Etudiants.N13213316[birthDate]

refers to the birthDate variable - which is not to be confused with the "birthDate" string. This variable is actually not defined here - hence your error message.

You should either change your code to refer to a string:

this.Etudiants.N13213316["birthDate"]

or leave your code as is, but declare the birthDate variable beforehand as pointing to the "birthDate" string:

var birthDate = "birthDate"

Note that you may run into other issues here though:

  • If your code runs in strict mode, this will be undefined here - in which case this.Etudiants will trigger a TypeError .
  • Even if your code runs in non-strict mode, at the time the this.Etudiants expression is evaluated here, it actually is undefined - the assignment to the Etudiants variable has not happened yet -, so this.Etudiants.N13213316 will cause a TypeError.

Edit: to solve the later point, you would need to defer executing the this.Etudiants.N13213316 expression until after the initial assignment to the Etudiants variable has actually happened. One simple solution would be as follows:

var Etudiants = {
"N13213316" : {
    "name" : "Touati Mohammed",
    "birthDate" : "05 June 2001",
    "isStudent" : true,
    "departement" : {
            "2021" : "USMBA ENCG Fes",
            "2021" : "USMBA FLDM Fes"
    }
}
}
Etudiants.N13213316.age = (Math.round((new Date().getTime() - new Date(Etudiants.N13213316["birthDate"]).getTime()) / 1000 / 60 / 60 / 24 / 365.25)),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM