0

Is there a way to loop through an array (or something similar) when generating js code? For example, I have this in mongoose:

    users.updateOne({'_id': req.user._id}
                , {
                ["local.minMinutes"]: req.body.minMinutes

                , ["local.color1U"]: req.body.color1U
                , ["local.color2U"]: req.body.color2U
                , ["local.color3U"]: req.body.color3U
                , ["local.color4U"]: req.body.color4U
                , ["local.color5U"]: req.body.color5U
});

I'd like to be able to say "loop through 1 to 5" instead of having to write each individual number out, but a for() loop inside the mongoose call is giving all sorts of error. I hope this question is specific enough - thank you!

2
  • Are you using something like Lodash which has better map-type methods? Commented Oct 9, 2019 at 16:31
  • I'm currently using node.js with express if that's any help... Commented Oct 9, 2019 at 16:33

1 Answer 1

1

Use a for loop to create the object by copying the properties from req.body.

obj = {
};
for (prop in req.body) {
    obj[`local.${prop}`] = req.body[prop];
}
users.updateOne({'_id': req.user._id}, obj);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.