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

339
Views
Get a property of an object using forEach even though it doesn't exist

What I basically have is an array of objects with several properties, but not all of them have the same properties.

const data = [
      {
        car: 12,
        airplane: 42,
        peoples: 2,
      },
      {
        car: 12,
        peoples: 2,
      },
      {
        car: 12,
        airplane: 42,
        peoples: 2,
      },
    ];

What I want to do is apply a filter() to filter the objects with the condition below. The problem is that there are objects with these properties missing and consequently the code ends up breaking. What is the best way to do this without breaking the code?

data.forEach((item) => item.airplane > 5);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Using Array#filter:

const data = [ { car: 12, airplane: 42, peoples: 2 }, { car: 12, peoples: 2 }, { car: 12, airplane: 42, peoples: 2 } ];

const res = data.filter(({ airplane }) => airplane && airplane > 5);

console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

Your most succinct option here is to use optional chaining (?.) and the nullish coalescing operator (??) -- the combination of these two allow you to use some fallback option when some property in the chain is missing. So you would rewrite your callback as:

(item) => (item?.airplane ?? 0) > 5

In the case that item.airplane is defined, you will get the calculation as expected. If it is not, it will fallback to assessing 0 > 5.

about 4 years ago · Juan Pablo Isaza Report

0

You need to use filter() and you need to expand a little on your filter logic to check for the property -

const result = data.filter((item) => item.airplane && item.airplane > 5)
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!