javascript - 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);
解决方案
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.
推荐阅读
- java - HTTP 状态 500 – Servlet-JSP 中的内部服务器错误
- swift - 如何从本地存储加载数据...我尝试了很多东西但没有任何效果
- c# - Asp.Net Core - 在响应返回后需要服务时如何处理服务生命周期?
- python - 在dict中查找基于键的值长度
- r - 为什么我的前导函数会生成 NA 值?
- junit4 - 如何从 junit 测试生成 spring restdocs 和 Pact.io 协议?
- c++ - 指向成员类型和模板的指针
- recaptcha - 可以使用 api 创建 google recaptcha 站点和密钥吗
- class - 八度类成员变量更改不起作用
- laravel - Laravel 监听 socket.io 客户端发出