0

I have two objects:

Group which has a users property, containing an array of ObjectIds:

["59f5c8b62f73d036bc4f5673","59f5c7d42f73d036bc4f566b",
"59f5c81a2f73d036bc4f566d","59f5c8482f73d036bc4f566f"]

And another object which has a property which needs to be populated with that exact array of objectIds, so when I create it in the back, it looks like this right now:

var object = new Object({
      title: req.body.title
      group: req.params.id,
      objectArray: { user: group.users, value: 1 }
    });

I am expecting to get the population as follows:

object: {
    title: some-title,
    group: someRefId,
    objectArray: [ 
       {user: ObjectId1, value: 1},
       {user: ObjectId2, value: 1},
       {user: ObjectId3, value: 1},
       {user: ObjectId4, value: 1}
    ]
}

I need to iterate through that array somehow and then declare {user: user of group.users, value:1} or something. I don't understand how to iterate through that array while declaring a new object...

1
  • You may want to look at Array.prototype.map. Commented Nov 6, 2017 at 0:13

2 Answers 2

4

var req = {
  body: {
    title: 'some-title'
  },
  params: {
    id: 'someRefId'
  }
};

var group = {
  users: [
    "59f5c8b62f73d036bc4f5673",
    "59f5c7d42f73d036bc4f566b",
    "59f5c81a2f73d036bc4f566d",
    "59f5c8482f73d036bc4f566f"
  ]
};

var object = {
  title: req.body.title,
  group: req.params.id,
  objectArray: group.users.map(function(user) {
    return {
      user: user,
      value: 1
    };
  })
};

console.log(object);

Sign up to request clarification or add additional context in comments.

Comments

1

You could use Array.prototype.map to do this.

ES6

...
objectArray: group.users.map((user) => ({ user, value: 1 }))
...

ES5

...
objectArray: group.users.map(function (user) {
    return { 
        user: user, 
        value: 1 
    };
})
...

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.