javascript - 如何在 javascript 中使用 map 函数迭代嵌套字典
问题描述
我正在尝试使用 map 迭代字典。但我无法获得嵌套字典属性。例如,我需要 value.type==string 的密钥。有人可以帮我吗?
数据.js
const products_schema = {
_id: {
auto: true
},
product_name: {
auto: false,
type: "string",
min: 5,
max: 10,
special_characters: ['_', ' '],
numbers: true,
alphabet: true,
required: true,
correct: ""
},
product_image: {
auto: false,
type: "array:string",
min: 0,
max: 50,
required: true
},
product_specification: {
auto: false,
type: "array:specification_schema",
min: 0,
max: 50,
required: true
}
}
}
let schema=new Map()
schema.set('products_schema',products_schema)
for([key,value] of schema.entries()){
console.log(value.type) //shows undefined in the console
}
解决方案
我不知道为什么需要使用 Map 对象,但是对于这种遍历对象的情况,您可以尝试使用旧的for..in循环,该循环遍历products_schema
对象的可枚举属性。
const products_schema = {
_id: {
auto: true
},
product_name: {
auto: false,
type: "string",
min: 5,
max: 10,
special_characters: ['_', ' '],
numbers: true,
alphabet: true,
required: true,
correct: ""
},
product_image: {
auto: false,
type: "array:string",
min: 0,
max: 50,
required: true
},
product_specification: {
auto: false,
type: "array:specification_schema",
min: 0,
max: 50,
required: true
}
};
for (const key in products_schema){
console.log(key);
for (const inner in products_schema[key]){
console.log(`${inner}:${products_schema[key][inner]}`);
}
}
推荐阅读
- sql - sql中的按位运算
- postgresql - psycopg2.errors.UndefinedColumn:列已排除。编号不存在
- video - 为用户跟踪和保存视频进度
- java - 当 Activity Swipe 上的 CardStackView 时如何停止适配器上的 MediaPlayer?
- c# - C# 控制台应用程序不会在其他人的计算机上运行
- html - How to Create Date Count timer selecting date from the date picker input and show the difference of selected date to current date
- laravel - Laravel - 如何将所有导入错误保存到表中
- python - 条形图中的颜色
- swagger - OpenAPI 3.0:C++ 服务器存根和客户端 SDK
- javascript - 如何从 Angular js 数组中过滤