首页 > 解决方案 > 如何在 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
}

标签: javascript

解决方案


我不知道为什么需要使用 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]}`);
  }
}


推荐阅读