gpt4 book ai didi

javascript - 将 js 数组转换为字典/ HashMap

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:07 30 4
gpt4 key购买 nike

我正在尝试将对象数组转换为 HashMap 。我只有 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 结果是一个索引从 0 开始的 Object。希望只有一件我看不到的小事。但目前我的脑子里在想如何将一个简单的数组转换成一个类似 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.

最佳答案

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

输出:

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

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

关于javascript - 将 js 数组转换为字典/ HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50802528/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com