Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
Is there a way to only add a property if it is defined via the spread operator?

I have a variable name and I want to add it to an object only if it's defined and not null. For example, I check the value of name:

let name = null;
if(nameExists) {
    name = 'John Smith';
}

Then I only want to add it to the object as a field if it exists and is not null.

const results = {
   title: $(el).find('.title').text(), 
   name
};

But this doesn't work. Any ideas?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Well, to do that, you have to spread an object containing the property or an empty object, depending on whether you want to add the property:

const results = {
   title: $(el).find('.title').text(), 
   ...(
     name !== null
       ? {name}
       : {}
   )
};

But I think a conditional assignment could be clearer:

const results = {
   title: $(el).find('.title').text()
};

if(name !== null)
  results.name = name
about 4 years ago · Juan Pablo Isaza Denunciar

0

I hope this example clears your concept.

function addName(name) {
    let obj = {"site":"stackoverflow"}; // create an object)=(it may be pre-existing)
    if(name) {
        obj = {...obj, name}; // add name field to obj only if it exists
    }
    return obj;
}

const ex1 = addName();
const ex2 = addName('John Smith');
console.log('If name is null: ', ex1);
console.log('If name exists: ', ex2);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda