How to set conditional properties for a literal object in the simplest way possible with Javascript?

2

I'd like to know how to add conditional properties to a literal object in the simplest possible way.

I currently declare the object and then add the conditional properties as in the following example:

function getFamilia(avos) {
  const familia = {
    filhos: ['Pedro', 'Claudia'],
    pais: ['Marcio', 'Fernanda']
  }

  if (avos) {
     familia.avos = avos
  }

  return familia
}

I have tried to make a ternary in the definition of the object but the key is still there even if it returns undefined. Example:

const getFamilia = avos => ({
  filhos: ['Pedro', 'Claudia'],
  pais: ['Marcio', 'Fernanda'],
  avos: avos || undefined
})

Is there any way to do conditionals directly in the object declaration without leaving the key there in the false case?

You can use any feature of any version of javascript.

    
asked by anonymous 28.03.2017 / 15:16

2 answers

1

Your object creation is in the wrong definition. What you are doing is a function that returns an object and not a class in javascript. With a class you can ensure that the attribute exists since it is defined in it.

/*
 *  JS Class
 *
  function Familia(filhos, pais, avos) {
    if(filhos) this.filhos = filhos;
    if(pais) this.pais = pais;
    if(avos) this.avos = avos;
  }
/*
 */
 
/*
 *  ES6 Class
 */
class Familia {
  constructor(filhos, pais, avos) {
    if(filhos) this.filhos = filhos;
    if(pais) this.pais = pais;
    if(avos) this.avos = avos;
  }
}
/*
 */
 

let familiaCompleta = new Familia(['Pedro', 'Claudia'], ['Marcio', 'Fernanda'], ['Frank']);
console.log(familiaCompleta);

let semFilhos = new Familia(null, ['Marcio', 'Fernanda'], ['Frank']);
console.log(semFilhos);

let semPais = new Familia(['Pedro', 'Claudia'], null, ['Frank']);
console.log(semPais);

let semAvos = new Familia(['Pedro', 'Claudia'], ['Marcio', 'Fernanda'], null);
console.log(semAvos);
    
28.03.2017 / 15:52
0

It is possible to resolve the action of defining this property (recognized as [[PUT]] by the specifications of the ECMAScript, or "set"), or the read ([[GET]], or "get") in the object. This is only directly available in ECMAScript 5 and above (especially in ECMAScript 6).

Creating a Proxy you can control all actions of [[PUT]] at once (looks a lot like the meta (tables of the Lua)) on the same object.

const meta = {
    set: (f, prop, value) => {
        // Toda propriedade deve conter um objeto.
        if (value instanceof Object) {
            f[prop] = value
            return true
        }
        // Não redefine a propriedade nesse caso.
        return false
    }
}

const getFamilia = avos => {
    var init = {
        filhos: ['Pedro', 'Claudia'],
        pais: ['Marcio', 'Fernanda']
    }
    var f = new Proxy(init, meta)
    f.avos = avos
    return f
}

Proxy comes from ES6.

    
28.03.2017 / 16:57