Trying to replace forEach with map

Why can I not replace forEach with map() in this instance? Or maybe the better question is, HOW can I successfully replace forEach() with map()? Does it have anything to do with the fact that one of the keys (24hr_vol) errors out because it begins with a number…?

forEach() code:

  for (var coin in data) {
    if (!data.hasOwnProperty(coin)) {
    filteredData[coin] = data[coin].filter(function(d) {
      return !(d["price_usd"] == null);
    filteredData[coin].forEach(function(d) {
      d["price_usd"] = +d["price_usd"];
      d["24h_vol"] = +d["24h_vol"];
      d["market_cap"] = +d["market_cap"];
      d["date"] = parseTime(d["date"]);

map() code:

  for (let eachItem in data) {
    cleanData[eachItem] = data[eachItem]
      .filter(function(d) {
        return !(d["price_usd"] == null);
      .map(function(d) {
        let clean24hrvol = parseInt(d["24h_vol"]);
        let cleanDate = parseTime(d["date"]);
        let cleanMktcap = parseInt(d["market_cap"]);
        let cleanPrice = parseInt(d["price_usd"]);
        let eachObj = {
          // 24h_vol: clean24hrvol, //This key begins with a number causing errors.
          date: cleanDate,
          market_cap: cleanMktcap,
          price_usd: cleanPrice
        return {

Your code seems correct but for better debug you provide a sample of the data to make it easier?

All the same, I can answer you that yes, you do have an error by having the property of an object start with a number.

The following will error out

let eachObj = {
  24h_vol: clean24hrvol

This way it won’t error out

let eachObj = {
  "24h_vol": clean24hrvol

While it is valid to leave it just as a number it can cause unexpected behaviors in a for…in

let eachObj = {
  24: clean24hrvol

As a rule of thumb, I would use always alpha (a-z) as the first letter of a variable name.

Side note, if you want to read a bit more of the topic I’ve done a small article that glances over that and has some examples of the unexpected behavior. You can read here

1 Like