首页 > 解决方案 > Trying to create a dictionary of clothes available in store in javascript

问题描述

Hi guys, I'm trying to display my dictionary map like so:

"black": { 
      "XS": 1, 
      "M": 1, 
      "L": 1, 
      "XL": 2 
    }, 
    "white": { 
      "XS": 1, 
      "L": 1 
    }, 
    "red": { 
      "M": 1 
    }, 
    "blue": { 
      "2XL": 3, 
      "S": 1 
    }

the data given was written like this:

  const products = [
  "black-XS", 
  "black-M", 
  "black-L", 
  "black-XL", 
  "black-XL", 
  "white-XS", 
  "white-L", 
  "red-M", 
  "blue-2XL", 
  "blue-2XL", 
  "blue-2XL", 
  "blue-S"]        

and I wrote this code:

  let Black = new Map();
  let blackSize = new Map();
  blackSize["XS"] = 1;
  blackSize["M"] = 1;
  blackSize["L"] = 1;
  blackSize["XL"] = 2;
  Black["black"] = blackSize;
  console.log(Black);

  let White = new Map();
  let whiteSize = new Map();
  whiteSize["XS"] = 1;
  whiteSize["L"] = 1;
  White["white"] = whiteSize;
  console.log(White);

  let Red = new Map();
  let redSize = new Map();
  redSize["M"] = 1;
  Red["red"] = redSize;
  console.log(Red);

  let Blue = new Map();
  let blueSize = new Map();
  blueSize["2XL"] = 3;
  blueSize["S"] = 1;
  Blue["blue"] = blueSize;
  console.log(Blue);

but that returns:

console.log
    Map { blue: Map { XS: 1, M: 1, L: 1, XL: 2 } }

      
  console.log
    Map { white: Map { XS: 1, L: 1 } }

      
  console.log
    Map { red: Map { M: 1 } }

      
  console.log
    Map { blue: Map { 2XL: 3, S: 1 } }

I'm still a newbie in programming, so I've been trying to figure it out how to use .forEach or for ... in ... so I don't even need to rewrite the data given and extract directly from it, but I've been failing at it. So I tried to use map as a way to display the info, but I'm still not getting to the final answer. Can you guys give me some light?

EDIT

The answer from @Alexey is the better one, more generic and can be applied to any generic shopping item, but I also managed to rearrange my original code like this, using @geofh tip:

  let Shirts = {};
  let blackSize = {};
  blackSize["XS"] = 1;
  blackSize["M"] = 1;
  blackSize["L"] = 1;
  blackSize["XL"] = 2;
  Shirts["black"] = blackSize;
  
  let whiteSize = {};
  whiteSize["XS"] = 1;
  whiteSize["L"] = 1;
  Shirts["white"] = whiteSize;
  
  let redSize = {};
  redSize["M"] = 1;
  Shirts["red"] = redSize;
  
  let blueSize = {};
  blueSize["2XL"] = 3;
  blueSize["S"] = 1;
  Shirts["blue"] = blueSize;

  return(Shirts);

标签: javascriptarraysdictionary

解决方案


You can replace each occurrence of new Map() with {}. That will get you much closer I think!

Hard to apply .forEach here, since the numbers you want in your output are not expressed in the input ... so you are hard-coding it. If you reformulate the input to include those numbers, there might exist a more generic solution.


推荐阅读