【发布时间】:2021-03-02 09:34:24
【问题描述】:
使用reduce操作对象数组,缺少正确的类型
我从 API 响应中获取了我需要操作的数组,然后才能在我的节点应用程序中使用它。
这是我已经在我的应用中所做的:
const array = [
{
users: {
'bc1bff64-ecde-4500-b16d-c1d3a37f2558': {
points: 368,
user_id: 'bc1bff64-ecde-4500-b16d-c1d3a37f2558',
period: 6,
city: 'london'
},
'5124be0c-3faf-444d-9e83-b570ca42c772': {
points: 358,
user_id: '5124be0c-3faf-444d-9e83-b570ca42c772',
period: 6,
city: 'london'
}
}
},
{
users: {
'bc1bff64-ecde-4500-b16d-c1d3a37f2558': {
points: 368,
user_id: 'bc1bff64-ecde-4500-b16d-c1d3a37f2558',
period: 6,
city: 'paris'
},
'5124be0c-3faf-444d-9e83-b570ca42c772': {
points: 358,
user_id: '5124be0c-3faf-444d-9e83-b570ca42c772',
period: 6,
city: 'paris'
}
}
},
{
users: {
'bc1bff64-ecde-4500-b16d-c1d3a37f2558': {
points: 0,
user_id: 'bc1bff64-ecde-4500-b16d-c1d3a37f2558',
period: 5,
city: 'london'
},
'5124be0c-3faf-444d-9e83-b570ca42c772': {
points: 0,
user_id: '5124be0c-3faf-444d-9e83-b570ca42c772',
period: 5,
city: 'london'
}
}
},
{
users: {
'bc1bff64-ecde-4500-b16d-c1d3a37f2558': {
points: 0,
user_id: 'bc1bff64-ecde-4500-b16d-c1d3a37f2558',
period: 5,
city: 'paris'
},
'5124be0c-3faf-444d-9e83-b570ca42c772': {
points: 0,
user_id: '5124be0c-3faf-444d-9e83-b570ca42c772',
period: 5,
city: 'paris'
}
}
}
];
const getPeriodName = (period: number) =>
({ 5: 'PERIOD_5_NAME', 6: 'PERIOD_6_NAME' }[period]);
const getCityName = (city: string) =>
({ 'london': 'London', 'paris': 'Paris' }[city]);
const getPointsGain = (points: number) => points + 'blabla';
const reduced = array.reduce((acc, { users }) => {
Object.entries(users)
.map(([id, { ...all }]) => {
acc[id] = acc[id] || {
id, periods: {}
};
acc[id].periods[all.period] = acc[id].periods[all.period] || {
name: getPeriodName(all.period),
cities: {}
};
acc[id].periods[all.period].cities[all.city] = {
name: getCityName(all.city),
points: all.points,
pointsGain: getPointsGain(all.points)
};
});
return acc;
}, {});
const result = Object.values(reduced);
console.log('result', result);
问题是 reduced 是类型 {} 空对象而不是正确的完整类型
“正确”类型的示例
我想以正确的类型结束这个数组:
[
{
"id": "bc1bff64-ecde-4500-b16d-c1d3a37f2558",
"periods": {
"5": {
"name": "PERIOD_5_NAME",
"cities": {
"london": {
"name": "London",
"points": 0,
"pointsGain": "0blabla"
},
"paris": {
"name": "Paris",
"points": 0,
"pointsGain": "0blabla"
}
}
},
"6": {
"name": "PERIOD_6_NAME",
"cities": {
"london": {
"name": "London",
"points": 368,
"pointsGain": "368blabla"
},
"paris": {
"name": "Paris",
"points": 368,
"pointsGain": "368blabla"
}
}
}
}
},
{
"id": "5124be0c-3faf-444d-9e83-b570ca42c772",
"periods": {
"5": {
"name": "PERIOD_5_NAME",
"cities": {
"london": {
"name": "London",
"points": 0,
"pointsGain": "0blabla"
},
"paris": {
"name": "Paris",
"points": 0,
"pointsGain": "0blabla"
}
}
},
"6": {
"name": "PERIOD_6_NAME",
"cities": {
"london": {
"name": "London",
"points": 358,
"pointsGain": "358blabla"
},
"paris": {
"name": "Paris",
"points": 358,
"pointsGain": "358blabla"
}
}
}
}
}
]
【问题讨论】:
标签: javascript arrays typescript reduce