简体   繁体   English

ES6 将两个变量组合成一个现有的 javaScript 对象

[英]ES6 combine two variables into an existing javaScript object

I'm currently returning createdAt and updatedAt outside of the data object, I want to add them to the data object so I can return a single object.我目前正在返回createdAtupdatedAt数据对象之外,我想将它们添加到数据对象,所以我可以返回一个对象。

I've also noticed I'm getting $init: true from somewhere, how to get rid of this?我也注意到我从某个地方得到$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 });
    }
  };

The current result is目前的结果是

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"

Use spread operator:使用扩展运算符:

{ ...data, updatedAt, createdAt }

Be warning, your variable name gonna be your index警告,你的变量名将成为你的索引

To remove $init but nothing else.删除$init但没有别的。

const {$init, ...cleanData} = data;

To create a data object with createdAt and updatedAt要创建一个数据对象createdAtupdatedAt

const finalData = {...cleanData, createdAt, updatedAt}

Happy coding!快乐编码!

Just use .toObject() like so:只需像这样使用 .toObject() :

static profile = async (req: Request, res: Response) => {
try {
  const { username } = req.params;
  const _account = await userModel
    .findOne({ 'shared.username': username })
    .exec();
  const account = _account.toObject()
  if (account) {
    const {email, loggedIn, location, warningMessage, ...data} = account.shared;
    const { updatedAt, createdAt } = account;
    res
      .status(200)
      .send({ data: { ...data, ...{ updatedAt, createdAt }} });
  } else res.status(400).send({ message: 'Server Error' });
} catch (error) {
  res.status(400).send({ message: 'Server Error', error });
}

}; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM