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

126
Views
is it possible to make spread operator ignore undefined propperties

Given the following

[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
  return {
    ...x,
    b: undefined
  }
})

I would like to end up with something like

[{a:5},{a:2})

Is that possible? I know I could do something like

[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
const obj = {
    ...x,
  }
  delete obj.b
  return obj
})

or

[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
  return {
    a: x.a
  }
})

The first method results in the values just being set to "undefined". The second method seems wasteful for larger arrays as a new variable is created object, and also my typescript complains about it because the original property wasn't optional. The third method works if you only want to retain a small number of properties, but once it gets over just a few properties it just seems unwieldy. For my current case, I'll probably opt for the second method, but I am curious if there's a way to handle this more elegantly.

I'm aware that I can also do something like:

Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])

But it still doesn't seem all that elegant.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can just ignore the b and collect all properties in rest and then spread the rest in the final result.

You can also make it one liner

const result = arr.map(({ b, ...rest }) => rest);

const arr = [
  { a: 5, b: 2 },
  { a: 2, b: 5 },
]
const result = arr.map(({ b, ...rest }) => rest);

console.log(result);

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!