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

69
Views
Condition Spread based on Object props

I'm looking for way to remove empty or null props, on my example obj2, I want to avoid copying the birthPlace property or any other prop that comes empty.

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...obj1, ...obj2 };

Desired result:

{firstName: 'Foo', age: 22, lastName: 'Bar', gender: 'M'}

Is it possible using Conditional Objects props using Spread Operators in javascript?

const updateUserObj = {
  ...(obj1 !== check here<hasPropEmpty> && obj2)
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

There's no shorthand for it, but you can easily write a function that filters out those properties.

function nonEmptyProps(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([k, v]) => v !== null && v !== ''));
}

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = {...nonEmptyProps(obj1), ...nonEmptyProps(obj2)};
console.log(newObj);

about 4 years ago · Juan Pablo Isaza Report

0

Using Object#entries you get the key-value pairs of an object, then, using Array#filter you iterate over these pairs to filter out the ones with empty values. Then, using Object#fromEntries you construct back the resulting pairs to an object.

const filterProps = (obj = {}) => 
  Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => 
      value !== null && value !== undefined && value !== ''
    )
  );

const obj1 = { firstName: 'Foo', age: 22 };
const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...filterProps(obj1), ...filterProps(obj2) };

console.log(newObj);

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!