我试图将对象数组转换为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
原来是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
。
答案 0 :(得分:3)
使用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
(注意,在用作地图的对象中,属性的顺序并不重要 - 如果您需要特定的顺序,请使用数组。)
答案 1 :(得分:0)
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));
答案 2 :(得分:0)
也可以使用 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);