Seeking help to retrieve a nested property name in an object while constructing the object.
What could be the issue here? How can I obtain the desired output: 'c'
from the nested object?
Source of reference: MDN documentation
const obj = {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
};
console.log(obj.latest);
// Expected result: "c"
// Current result: "c"
The provided example above is functional as expected.
However, my goal is to introduce nesting (obj.level1
). Here is where I encounter difficulties.
First modification attempt: unsuccessful
const obj = {
level1: {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
}
};
console.log(obj.latest);
// Desired outcome: "c"
// Result received: undefined
Second modification attempt: unsuccessful
const obj = {
level1: {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.level1.log.length - 1];
}
}
};
console.log(obj.latest);
// Desired output: "c"
// Output obtained: undefined