Home > Blockchain >  Use object property inside another property as function
Use object property inside another property as function

Time:12-28

I'm willing to create an object in js as follows:

var item = {
      id:'skate',
      nombre:'electric skate',
      status: StatusByDate(this),    
      enddate: new Date(2022,01,31),
    }

and also have this function to work with the enddate property:

function StatusByDate(obj){
      let hoy = Date.now();
      if(obj.enddate > hoy){
        return "ACTIVE";
      } else {
        return "ENDED";
      }
}

However, I'm getting Cannot read properties of undefined (reading 'enddate'), I'm not sure if a property of the object can be used inside a function placed in another property.

Secondly, I'm also interested in good practices, if there is a better way to do this, please let me know.

CodePudding user response:

Using a getter:

function StatusByDate(obj) {
  const hoy = new Date();
  if(obj.enddate > hoy) {
    return "ACTIVE";
  } else {
    return "ENDED";
  }
}

const item = {
  id: 'skate',
  nombre: 'electric skate',
  enddate: new Date(2022, 01, 31),
  get status() { return StatusByDate(this); }
}

console.log(item);

CodePudding user response:

Your code doesn't work because you're trying to reference the object during its creation. However you can create the item, then add its status afterwards as seen in the code below.

var item = {
      id:'skate',
      nombre:'electric skate',   
      enddate: new Date(2022,01,31),
    }

function StatusByDate(obj){
      let hoy = Date.now();
      if(obj.enddate > hoy){
        return "ACTIVE";
      } else {
        return "ENDED";
      }
}

// set the status after the object exists, not during creation
item.status = StatusByDate(item);
console.log(item);

CodePudding user response:

I finally decided to create a class with a constructor so I can apply functions inside of it and get the result right away.

class Sorteo{
constructor(id,nombre,status,enddate){
    this.id = id;
    this.nombre = nombre;
    this.estado = setEstadoByDate(enddate);   

function setEstadoByDate(ffin){
        let hoy = Date.now();
        console.log(ffin);
        if(ffin > hoy){
          return "ACTIVO";
        } else {
          return "FINALIZADO";
        }
    }

}
  • Related