Kin*_*sin 8 javascript typescript
我正在尝试将对象数组转换为哈希图。我只有 ES6 的某些部分可用,我也不能使用Map
。
数组中的对象非常简单,例如{nation: {name: string, iso: string, scoringPoints: number}
. 我需要对它们进行排序scoringPoints
。我现在想要一个按 iso -> 排序的“字典” {[iso:string]:number}
。
我已经尝试过(从这里 (SO))
const dict = sortedData.reduce((prev, curr, index, array) => (
{ ...array, [curr.nation.iso]: ++index }
), {});
Run Code Online (Sandbox Code Playgroud)
但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));
Run Code Online (Sandbox Code Playgroud)
正在显示
{
"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
}
Run Code Online (Sandbox Code Playgroud)
在控制台中。
根据评论,我想要的是一个类似哈希图的对象
{
"HU": 1,
"DE": 2,
"RS": 3
}
Run Code Online (Sandbox Code Playgroud)
其中属性值是排序数据中的排名(+1),因此我可以通过访问dict["DE"]
which 将返回2
.
jsp*_*cal 10
使用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'])
Run Code Online (Sandbox Code Playgroud)
输出:
{
"SR": 3,
"DE": 2,
"HU": 1
}
dict['DE'] = 2
Run Code Online (Sandbox Code Playgroud)
(请注意,在用作映射的对象中,属性的顺序并不重要 - 如果您需要特定的顺序,请使用数组。)
也可以使用 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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16511 次 |
最近记录: |