I want to get a nested property name in an object during object construction.
What am I doing wrong? How do I get the expected output: 'c'
from the nested object?
Starting point: MDN documentation
const obj = {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
};
console.log(obj.latest);
// Expected output: "c"
// Actual output: "c"
Confirmed. The above starting example works.
Now, I want to add nesting (obj.level1
). This is where things fall apart.
Modification attempt 1: not working
const obj = {
level1: {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
}
};
console.log(obj.latest);
// Expected output: "c"
// Actual output: undefined
Modification attempt 2: not working
const obj = {
level1: {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.level1.log.length - 1];
}
}
};
console.log(obj.latest);
// Expected output: "c"
// Actual output: undefined
2
Answers
In your modifications
obj
doesn’t havelatest
getter. It’s in child objectlevel1
, so just try loggingobj.level1.latest
.Your
latest
function exists on thelevel1
depth. So the following works:However, if that’s not your intention, you should write your object as such.