我当前正在数据对象外部返回 createdAt
和 updatedAt
,我想将它们添加到数据对象中,以便可以返回单个对象。
我还注意到我从某个地方得到了 $init: true
,如何摆脱它?
static profile = async (req: Request, res: Response) => {
try {
const { username } = req.params;
const account = await userModel
.findOne({ 'shared.username': username })
.exec();
if (account) {
const {email, loggedIn, location, warningMessage, ...data} = account.shared;
const { updatedAt, createdAt } = account;
res
.status(200)
.send({ data, updatedAt, createdAt }); // <=== How to combine updatedAt & createdAt into data?
} else res.status(400).send({ message: 'Server Error' });
} catch (error) {
res.status(400).send({ message: 'Server Error', error });
}
};
当前结果是
createdAt: "2019-12-13T12:15:05.031Z"
data: {
$init: true // <=== why is this here, where did it come from?
avatarId: "338fcdd84627317fa66aa6738346232781fd3c4b.jpg"
country: "AS"
fullName: "Bill"
gender: "male"
language: "en"
username: "bill"
}
updatedAt: "2019-12-14T16:07:34.923Z"
最佳答案
使用扩展运算符:
{ ...data, updatedAt, createdAt }
警告,你的变量名将成为你的索引
关于javascript - ES6 将两个变量组合到现有的 javaScript 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59336954/