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

Viewed 151

I am new to JS and use node.js, express, and mongoose and have an incoming array with random and unpredictable key-value pairs.

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

I need to restructure this array in order to push it in my Mongo-database. So the result of the above restructured example needs to look like this:

// 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();

I've spent hours to restructure the simpleArray and am ending up with one options:

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

Problem: I don't like to log it to the console. I must provide it before 'await user.save();'. If I replace console.log() with return, suddenly it does not work anymore. What to do that it is made available for 'await user.save();' and store it in the database?? I googled a lot and there to often console.log() is used instead of practical ways of further using the code.

In the end it should work like this:

// 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();
1 Answers

I have the working solution:

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