Reputation: 469
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);
Upvotes: 1
Views: 1150
Reputation: 106
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.
Upvotes: 0
Reputation: 13623
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
.
Upvotes: 1
Reputation: 9571
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)
Upvotes: 0
Reputation: 28414
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);
Upvotes: 2