代码之家  ›  专栏  ›  技术社区  ›  MaYaN

如何迭代映射<string,string>?

  •  -3
  • MaYaN  · 技术社区  · 6 年前

    Map<string, string> :

    const foo = new Map<string, string>();
    
    // e.g. foo is one => "1", two => "2", three => "3" etc.
    

    我知道我可以用以下方法得到所有的钥匙:

    const keys = Object.keys(foo);
    

    但当我尝试使用以下公式获得每个对应的值时:

    keys.forEach(k => {const val = foo[k]});
    

    我得到以下错误:

    type Map<string, string> has no index signature.
    

    更新

    json 通过ajax调用接收到 映射<字符串,字符串>

    {
        one: "1",
        two: "2",
        three: "3"
    }
    

    然后我将执行以下操作:

    const response = await this.axios.get<Map<string, string>>("some/api");
    const foo = response.data;
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Patrick Roberts Benjamin Gruenbaum    6 年前

    你的问题并不表明你试图使用 foo.forEach() ,但它 尝试使用 keys.forEach() . const keys = Object.keys(foo) 获得一把钥匙 foo: Map<string, string> ,但它几乎肯定会返回一个空的 string[] .

    keys Map<string, string> 对它们进行迭代,你可以这样做:

    for (const key of foo.keys()) {
      // each key of foo
    }
    

    Array.from(foo.keys()).forEach(key => {
      // each key of foo
    })
    

    也, axios 从不返回 映射<字符串,字符串> Object ,或者可以使用更专门的类型,如 type Dictionary<T> = { [K: string]: T }

    const response = await this.axios.get<Dictionary<string>>("some/api");
    const foo = response.data
    const keys = Object.keys(foo)
    
    keys.forEach(key => { ... })
    
        2
  •  1
  •   Dom    6 年前

    使用时 Map.forEach .get 除非使用第3个参数,即映射本身,否则需要调用。

    const foo = new Map();
    
    foo.set('foo', 'bar');
    foo.set('bar', 'foo');
    
    foo.forEach(function(v, k, fooMap){
      console.log(`map key: ${k}, map value: ${v}, fooMap: ${fooMap.get(k)}`);
    })