Home > front end >  Get a property of an object using forEach even though it doesn't exist
Get a property of an object using forEach even though it doesn't exist

Time:09-21

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);

CodePudding user response:

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);

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

In your function, you can check if the item exists like so:

const result = data.filter(function(item) {
  if (item.airplane) {
    return item.airplane > 5;
  } else {
    return false;
  }
});

This even works in strict mode.

  • Related