簡體   English   中英

ES6 將兩個變量組合成一個現有的 javaScript 對象

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

我目前正在返回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 }

警告,你的變量名將成為你的索引

刪除$init但沒有別的。

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

要創建一個數據對象createdAtupdatedAt

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

快樂編碼!

只需像這樣使用 .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