Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!