Reputation: 801
I'm iterating over markers array and trying to filter out those places whose opening hours is undefined, however, I'm unable to filter out the undefined data. Below is my code and result:
const markers = data.map(place => {
if (typeof place. opening_now != 'undefined') {
return {
position: place.geometry.location,
content: place.name,
key: place.id,
opening_now: place.opening_now
};
}
(20) [undefined, {…}, {…}, undefined, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:undefined
1:{position: _.F, content: "San Francisco Marriott Union Square", key: "c904f2aae3fb8743f27bce36da94753a19b02131", opening_now : {open_now: true, weekday_text: Array(0)}}
2:{position: _.F, content: "Cornell Hotel De France", key: "547ceb15210b70b8734500183410bb10c644c395", opening_now :{open_now: true, weekday_text: Array(0)}}
3:undefined
4:{position: _.F, content: "San Francisco Marriott Marquis", key: "f007d2f91c0070ebdfec60275baa33623f0b771b", opening_now: {…}}
5:{position: _.F, content: "La Mar Cebicheria Peruana", key: "2dfcc4cf449104804f979d0c74583f2b3a48d046", opening_now: {…}}..
Upvotes: 0
Views: 180
Reputation: 63524
The reason why you're getting undefined
s in your output data is that map
operates on each element in the array. If your array is 10 elements long, your output array will also be 10 elements long. In your example you're just returning undefined
(ie "no object") when your opening_hours
is undefined
.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
So the filter
solution is quite tidy. It works the same as map
but only returns the elements that satisfy the condition you give the function.
ES6
const markers = data.filter(place => place.opening_now.open_now)
ES5 (which you might be more used to)
var markers = data.filter(function (place) {
return place.opening_now.open_now;
});
It removes the undefined
gaps in the array that you appear to have. This example, because you don't specifically express undefined
also removes instances of opening hours equalling null
if that's your bag.
Upvotes: 2
Reputation: 5210
Instead of map()
you can use filter(). filter()
works like map()
but instead of transforming values it will filter values by an boolean
. If a condition returns false
it will leave it out.
const makers = data.filter(place => place.opening_hours)
If place.opening_hours
is undefined
it will be convert into a false
and filter()
will leave this value out.
Upvotes: 0
Reputation: 613
first filter for defined objects, then for entries with opening hours.
const markers = data.filter((i) => i).filter((j) => j.opening_hours);
Upvotes: 0
Reputation: 1389
If you are only returning object elements from data then this should work:
const markers = data.filter(
place => typeof place.opening_hours != 'undefined'
);
Upvotes: 0