简体   繁体   English

将 js 数组转换为字典/哈希图

[英]Convert js Array to Dictionary/Hashmap

I'm trying to convert an array of objects into a hashmap.我正在尝试将对象数组转换为哈希图。 I only have some parts of ES6 available and I cannot use Map as well.我只有 ES6 的某些部分可用,我也不能使用Map

The objects in the array are quite simple, eg {nation: {name: string, iso: string, scoringPoints: number} .数组中的对象非常简单,例如{nation: {name: string, iso: string, scoringPoints: number} I need to sort them by scoringPoints .我需要通过scoringPoints对它们进行排序。 I want now a "dictionary" holding the rank by iso -> {[iso:string]:number} .我现在想要一个按 iso -> {[iso:string]:number}排序的“字典”。

I already tried (from here (SO) )我已经尝试过(从这里 (SO)

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

But dict turns out to be an Object with indices starting with 0 .dict原来是一个索引以0开头的Object Hopefully there is just a small thing I don't see.希望只是我没有看到的一件小事。 But currently my head is spinning how to convert a simple array into a hashmap-like object.但目前我的脑子在思考如何将一个简单的数组转换成一个类似 hashmap 的对象。 Maybe Array.map ?也许Array.map

I should also note that I am using TypeScript which I also had some trouble before when not typed correctly.我还应该注意,我使用的是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));  

is showing正在显示

{
    "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
}

in the console.在控制台中。

As per comments, what I want is a hashmap-like object like根据评论,我想要的是一个类似哈希图的对象

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

where the property-value is the rank (+1) in the sorted data so I can simply get the rank by accessing dict["DE"] which would return 2 .其中属性值是排序数据中的排名(+1),因此我可以通过访问dict["DE"]来简单地获得排名,这将返回2

Capture the position of each key in your data using forEach or reduce :使用forEachreduce捕获数据中每个键的位置:

 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'])

Output:输出:

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

(Note the order of properties is not significant in an object used as a map - if you need a specific order use an array.) (请注意,在用作映射的对象中,属性的顺序并不重要 - 如果您需要特定的顺序,请使用数组。)

 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) => b.nation.rankingPoints - a.nation.rankingPoints); const dict = sorted.reduce((result, curr, index, array) => ({ ...result, [curr.nation.iso]: ++index }), {}); console.log(JSON.stringify(dict));

It is also possible to achieve this using Array.map and Object.fromEntries:也可以使用 Array.map 和 Object.fromEntries 来实现:

 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 ? 1 : (a.nation.rankingPoints > b.nation.rankingPoints ? -1 : 0)); const dict = Object.fromEntries(sorted.map((c, index) => [c.nation.iso, index + 1])); console.log(dict);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM