我在使用REST在RESTful API中发送对象时遇到了一些麻烦。这应该很简单,但我有一个奇怪的错误。 这是我的代码:
result = result.map(function (elem) {
elem.progress = elem.progress.map(prog => prog.progress).reduce((x, y) => x + y, 0);
return ({'user': elem});
});
result.forEach((elem) => console.log('#', elem.user.progress));
console.log('result:', result);
res.send(result);
这是我用来测试它的数据:
[
{
"user": {
"user_id": 1,
"id": 354,
"already_connected": 1,
"progress": [
{
"id": 520,
"teams_user_id": 354,
"a_category_id": 1,
"progress": 100,
"created": "2016-11-10T13:44:30.000Z",
"modified": "2016-11-10T13:44:33.000Z"
},
{
"id": 521,
"teams_user_id": 354,
"a_category_id": 2,
"progress": 100,
"created": "2016-11-10T13:44:33.000Z",
"modified": "2016-11-10T13:44:35.000Z"
},
],
"user": {
"name": "Foo bar",
"avatar_id": 6673,
"default_avatar_int": 1
}
}
}
]
我希望进度等于200,这是我在res.send之前执行console.log时的情况,但是当我在Postman中接收数据时,进度仍然等于数组。我做错了什么?
答案 0 :(得分:0)
如果这是您最初使用的数据,那么您可能忘记导航到.user
属性。检查一下:
var result = [
{
"user": {
"user_id": 1,
"id": 354,
"already_connected": 1,
"progress": [
{
"id": 520,
"teams_user_id": 354,
"a_category_id": 1,
"progress": 100,
"created": "2016-11-10T13:44:30.000Z",
"modified": "2016-11-10T13:44:33.000Z"
},
{
"id": 521,
"teams_user_id": 354,
"a_category_id": 2,
"progress": 100,
"created": "2016-11-10T13:44:33.000Z",
"modified": "2016-11-10T13:44:35.000Z"
},
],
"user": {
"name": "Foo bar",
"avatar_id": 6673,
"default_avatar_int": 1
}
}
}
]
result = result.map(function (elem) {
// you forgot to navigate to `.user` property
elem.progress = elem.user.progress.map(prog => prog.progress).reduce((x, y) => x + y, 0);
return ({'user': elem});
});
result.forEach((elem) => console.log('#', elem.user.progress));
console.log('result:', result);