gpt4 book ai didi

node.js - 在 res.send 期间更改了 JS 对象

转载 作者:行者123 更新时间:2023-12-03 22:41:46 25 4
gpt4 key购买 nike

我在使用 Express 以 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
}
}
}
]

我期望progress等于200,这是我在res.send之前做console.log的情况,但是当我在Postman中接收数据时,progress仍然等于一个数组。我究竟做错了什么 ?

最佳答案

如果这是您最初使用的数据,那么您可能忘记导航到 .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);

关于node.js - 在 res.send 期间更改了 JS 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40589800/

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