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

将js数组转换为dictionary/hashmap

  •  2
  • KingKerosin  · 技术社区  · 8 年前

    我正在尝试将一个对象数组转换为哈希映射。我只有ES6的部分可用,不能使用 Map 也。

    数组中的对象非常简单,例如。 {nation: {name: string, iso: string, scoringPoints: number} . 我要把它们分类 scoringPoints . 我现在想要一本“字典”,它的排名是iso-> {[iso:string]:number} .

    我已经试过了 here (SO) )

    const dict = sortedData.reduce((prev, curr, index, array) => (
        { ...array, [curr.nation.iso]: ++index }
    ), {});
    

    但是 dict 原来是一个 Object 索引以 0 . 希望有一件小事我没看到。但目前我正在思考如何将一个简单的数组转换成类似hashmap的对象。 也许吧 Array.map ?

    我还应该注意到我正在使用 TypeScript 我以前打错字的时候也遇到过一些麻烦。

    const test = [
        { nation: { name: "Germany", iso: "DE", rankingPoints: 293949 } },
        { nation: { name: "Hungary", iso: "HU", rankingPoints: 564161 } },
        { nation: { name: "Serbia", iso: "SR", rankingPoints: 231651 } }
    ];
    
    const sorted = test.sort((a, b) => a.nation.rankingPoints - b.nation.rankingPoints);
    const dict = sorted.reduce((prev, curr, index, array) => ({ ...array, [curr.nation.iso]: ++index }), {});
    console.log(JSON.stringify(dict));  
    

    正在展示

    {
        "0": {
            "nation": {
                "name": "Serbia",
                "iso": "RS",
                "rankingPoints": 231651
            }
        },
        "1": {
            "nation": {
                "name": "Germany",
                "iso": "DE",
                "rankingPoints": 293949
            }
        },
        "2": {
            "nation": {
                "name": "Hungary",
                "iso": "HU",
                "rankingPoints": 564161
            }
        },
        "HU": 3
    }
    

    在控制台里。

    根据注释,我想要的是一个类似hashmap的对象

    {
        "HU": 1,
        "DE": 2,
        "RS": 3
    }
    

    其中属性值是排序数据中的秩(+ 1),因此可以简单地通过访问获得秩。 dict["DE"] 会回来的 2 .

    1 回复  |  直到 8 年前
        1
  •  4
  •   jspcal    8 年前

    使用 forEach 或 reduce :

    const test = [
        { nation: { name: "Germany", iso: "DE", rankingPoints: 293949 } },
        { nation: { name: "Hungary", iso: "HU", rankingPoints: 564161 } },
        { nation: { name: "Serbia", iso: "SR", rankingPoints: 231651 } }
    ];    
    
    const sorted = test.sort((a, b) => a.nation.rankingPoints - b.nation.rankingPoints);
    
    // Using forEach:
    
    var dict = {}
    sorted.forEach((el, index) => dict[el.nation.iso] = sorted.length - index);
    
    // Using reduce:
    
    dict = sorted.reduce(
        (dict, el, index) => (dict[el.nation.iso] = sorted.length - index, dict),
        {}
    );
    
    console.log(dict)
    console.log("dict['DE'] = ", dict['DE'])

    输出:

    {
      "SR": 3,
      "DE": 2,
      "HU": 1
    }
    dict['DE'] =  2
    

    (请注意,在用作映射的对象中,属性的顺序并不重要-如果需要特定顺序,请使用数组。)

    推荐文章