javascript - ES6 将两个变量组合到现有的 javaScript 对象中

标签 javascript node.js ecmascript-6

我当前正在数据对象外部返回 createdAtupdatedAt,我想将它们添加到数据对象中,以便可以返回单个对象。

我还注意到我从某个地方得到了 $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/

相关文章:

javascript - nodeJS 等待无法 promise 的事件

c++ - NodeJS Wrapped C++ 代码的函数故障是如何传播的?

javascript - 为什么以下函数在执行 `greet({ name = ' Rauno' } = {} )` instead of ` greet(name = 'Rauno')`?

javascript - ESlint linting gulpfile.js

javascript - 联系表中的隐藏字段

node.js - 如何根据nodejs中的分钟获取Twilio工作人员统计信息

javascript - .map 在未启动的数组上无法按预期工作

javascript - Object.prototypes 内置直接规则

javascript - 在 polymer 中的多个组件中初始化一个 Firebase 应用程序是否错误?

javascript - 如何将前导零的数字转换为字符串并保留原​​始数字