skip to Main Content

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


  1. In your modifications obj doesn’t have latest getter. It’s in child object level1, so just try logging obj.level1.latest.

    Login or Signup to reply.
  2. Your latest function exists on the level1 depth. So the following works:

    console.log(obj.level1.latest)
    

    However, if that’s not your intention, you should write your object as such.

    const obj = {
      level1: {
         log: ['a', 'b', 'c']
      },
      get latest() {
        return this.level1.log.at(-1);
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search