Ted
Ted

Reputation: 1760

Iterete thru map with [key, object] values

I have next map:

 const filter = new Map();

  filter.set('a1', {
    Day: 55,
    Type: 1,
  });

  filter.set('a2', {
    Day: 2,
    Type: 3,
  });

and I want to iterate thru it, by extracting only objects:

filter.values().map(({ Day, Type }) => {
  console.log(Day)
});

or

[...filter].map(({ Time, Type }) => {
  console.log(eventTime)
});

but I am getting error that map() is not function, or for second case it return Map item

p.s. I can't use for loops.

Upvotes: 0

Views: 64

Answers (3)

Nenad Vracar
Nenad Vracar

Reputation: 122047

To get and array of objects you can use spread syntax ... on map values that returns MapIterator. Then you can use any array method like forEach.

const filter = new Map();
filter.set('a1', { Day: 55, Type: 1 });
filter.set('a2', { Day: 2, Type: 3 });

console.log([...filter.values()])

Upvotes: 0

bakar_dev
bakar_dev

Reputation: 996

const filter = new Map();

  filter.set('a1', {
    Day: 55,
    Type: 1,
  });

  filter.set('a2', {
    Day: 2,
    Type: 3,
  });

for ( {Day,Type} of filter.values()) {
  console.log("Day: ",Day, "Type:",Type)
}

Upvotes: 1

Bergi
Bergi

Reputation: 664538

Map iterators don't have a map method (yet). You're probably looking for either forEach

filter.forEach(({ Day, Type }) => {
  console.log(Day)
});

or a simple for … of loop over the iterator:

for (const { Day, Type } of filter.values()) {
  console.log(Day)
}

Upvotes: 1

Related Questions