RamAlx
RamAlx

Reputation: 7334

Loop through an immutable Map in javascript

i'm a relatively newbie in javascript and i have to perform a task I have an immutable map:

Map({
 isNamed: true,
 isMarried: "",
 isMan: false
})

Now i have to loop through this Map and if a value is "" i must replace it with with false so my final Map is this:

isNamed: true,
 isMarried: false,
 isMan: false
})

I've used the forEach method like this:

const prepareData = cardData.forEach((value, key, map = {}) => {
      if (value === '') {
        map[key] = false;
      } else {
        map[key] = value;
      }
      return map;
    });

but the output is 0. What am i missing?

Upvotes: 0

Views: 237

Answers (2)

Prakash N
Prakash N

Reputation: 221

Well, there are a couple of issues with the implementation.

  1. forEach() always returns undefined.
  2. You need to use the Map instance methods to get, set or delete a value.
  3. You are mutating the existing Map object.

Upvotes: 0

Rostyslav
Rostyslav

Reputation: 2866

Here is how to do it:

for (let item of yourPreviousMap.entries()) {
  const [key, value] = item;
  if (value === '') {
    yourPreviousMap.set(key, false);
  }
}

Or if this code is too hard or you don't want to change the original map object, you can just go with creating a new map:

const yourNewMap = new Map();

yourPreviousMap.forEach((value, key) => {
  yourNewMap.set(key, value === "" ? false : value);
});

Upvotes: 1

Related Questions