0

What is the best practice for assigning a value to a key using a method that is in the parent object?

I have tried several variations of the following:

const data = {
  one : {
    a : {
      hours : 100,
      minutes : getMinutes()
    },
    b : {
      hours : 24,
      minutes : getMinutes()
    }
  },
  getMinutes : function() {
    return this.hours * 60
  }
}
Garland
  • 13
  • 4
  • 2
    Relevant: [Self-references in object literals / initializers](https://stackoverflow.com/q/4616202) – VLAZ Aug 08 '22 at 10:43
  • Define `function time(hours) { return {hours, minutes: hours*60}; }` then use `const data = {one: {a: time(24), b: time(100)}};` – Bergi Aug 11 '22 at 01:22

1 Answers1

0

This isn't really the intended purpose of objects. The best practice would be to create an outside function to get the value.

example:

const getMinutes = (hours) => {
    return hours * 60
  }
}
const data = {
  one : {
    a : {
      hours : 100,
      minutes : getMinutes(100)
    },
    b : {
      hours : 24,
      minutes : getMinutes(24)
    }
  }
}
Garland
  • 13
  • 4