javascriptimportobject-literalobject-properties

Fake object with Dynamic properties


I am trying to simulate a get request where the speed will change.

  export const fakeData = {
      timestamp: 1567606228,
      speed: generatespeed()
    };

    function generatespeed () {
      return Math.floor(Math.random() * 100);
    }

To simulate this in the page I simply import it and call it on a setInterval,

setInterval(() => {
    this.newData = fakeData;
}, 2000);

The speed however is the stays the same, I could just call the function but I would like to make the object properties change. Is this possible?


Solution

  • You are invoking the function while setting the value. You can use get here.

    export const fakeData = {
      timestamp: 1567606228,
      get speed(){ 
         return generatespeed()
      }
    };
    
    function generatespeed () {
      return Math.floor(Math.random() * 100);
    }