I'm getting this error "Uncaught TypeError: Cannot read properties of undefined (reading '0')" when I try to return the .Name
of my JSON
.
Here's my javascript (The console.log is for testing):
var roomsCodes = [
['232','DDSB'],
['232','DDMB'],
['232','SJJB'],
['232','SJJS'],
];
var jsonMin =
{
"DDSB": {
"Name": "Doble Estándar",
},
"DDMB": {
"Name": "Doble con vista mar",
},
"SJJB": {
"Name": "Jr. Suite",
},
"SJJS": {
"Name": "Jr. Suite Superior",
},
}
for(var p = 0; p < roomsCodes.length; p ){
if(232 == roomsCodes[p][0]){
console.log(jsonMin.roomsCodes[p][1].Name);
}
}
CodePudding user response:
You can fix it by using [] to access to the object, like this:
var roomsCodes = [
["232", "DDSB"],
["232", "DDMB"],
["232", "SJJB"],
["232", "SJJS"]
];
var jsonMin = {
DDSB: {
Name: "Doble Estándar"
},
DDMB: {
Name: "Doble con vista mar"
},
SJJB: {
Name: "Jr. Suite"
},
SJJS: {
Name: "Jr. Suite Superior"
}
};
for (var p = 0; p < roomsCodes.length; p) {
if (232 == roomsCodes[p][0]) {
console.log(jsonMin[roomsCodes[p][1]].Name);
}
}
When you want to access to a property using a dynamic variable you need to use square brackets otherwise you can use the dot.
CodePudding user response:
var roomsCodes = [
['232','DDSB'],
['232','DDMB'],
['232','SJJB'],
['232','SJJS'],
];
var jsonMin =
{
"DDSB": {
Name: "Doble Estándar",
},
"DDMB": {
Name: "Doble con vista mar",
},
"SJJB": {
Name: "Jr. Suite",
},
"SJJS": {
Name: "Jr. Suite Superior",
},
}
for(var p = 0; p < roomsCodes.length; p ){
if(232 == roomsCodes[p][0]){
const item = roomsCodes[p][1]
console.log(jsonMin[item].Name)
}
}