0

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?

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.