簡體   English   中英

Restructure object array with key value pairs in Javascript and output or emit it to save it with mongoose and MongoDB?

[英]Restructure object array with key value pairs in Javascript and output or emit it to save it with mongoose and MongoDB?

我是 JS 新手,使用 node.js、express 和 mongoose 並有一個帶有隨機和不可預測鍵值對的傳入數組。

 // Example
 const simpleArray = {
      d: "h",
      e: "i",
      f: "j",
      g: "k",
    };

我需要重組這個數組以便將它推送到我的 Mongo 數據庫中。 所以上面重構示例的結果需要如下所示:

// Restructured example
user.details.d.push({name:"h", date: Date.now(),});
user.details.e.push({name:"i", date: Date.now(),});
user.details.f.push({name:"j", date: Date.now(),});
user.details.g.push({name:"k", date: Date.now(),});

// After this restructering, I like to push it to the user database:
const user = await User.findById(userId);
await user.save();

我花了幾個小時來重組 simpleArray 並最終得到一個選項:

for (const [key, value] of Object.entries(basis)) {
      console.log(
        `user.details.${key}.push({name:"${value}", date: Date.now(),});`
      );
    }

問題:我不喜歡將它記錄到控制台。 我必須在'await user.save();'之前提供它。 如果我用 return 替換 console.log(),它突然就不再工作了。 做什么,它可用於 'await user.save();' 並將其存儲在數據庫中?? 我搜索了很多,並且經常使用 console.log() 代替進一步使用代碼的實用方法。

最后它應該像這樣工作:

// Example
     const simpleArray = {
          d: "h",
          e: "i",
          f: "j",
          g: "k",
        };

//Loop
     for (const [key, value] of Object.entries(basis)) {
          console.log(
            `user.details.${key}.push({name:"${value}", date: 
     Date.now(),});`
            );
          }
//Result
//user.details.d.push({name:"h", date: Date.now(),});
//user.details.e.push({name:"i", date: Date.now(),});
//user.details.f.push({name:"j", date: Date.now(),});
//user.details.g.push({name:"k", date: Date.now(),});



// Push to database
     const user = await User.findById(userId);
     await user.save();

我有工作解決方案:

 // Loop over random array
    Object.keys(simpleArray).forEach((item) => {
            user.details[item].push({
            name: simpleArray[item],
            date: Date.now(),
          });
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM