Home > Mobile >  How do getters work in nested objects when getting a property name from a nested object during objec
How do getters work in nested objects when getting a property name from a nested object during objec

Time:01-30

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

CodePudding user response:

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);
  }
};

CodePudding user response:

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

  • Related