我有两个对象:
Group
,其users
属性,包含一个ObjectIds数组:
["59f5c8b62f73d036bc4f5673","59f5c7d42f73d036bc4f566b",
"59f5c81a2f73d036bc4f566d","59f5c8482f73d036bc4f566f"]
另一个对象有一个属性,需要使用精确的objectIds数组填充,所以当我在后面创建它时,它现在看起来像这样:
var object = new Object({
title: req.body.title
group: req.params.id,
objectArray: { user: group.users, value: 1 }
});
我期待得到如下人口:
object: {
title: some-title,
group: someRefId,
objectArray: [
{user: ObjectId1, value: 1},
{user: ObjectId2, value: 1},
{user: ObjectId3, value: 1},
{user: ObjectId4, value: 1}
]
}
我需要以某种方式遍历该数组,然后声明{user: user of group.users, value:1}
或其他东西。我不明白如何在声明一个新对象时迭代该数组...
答案 0 :(得分: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);

答案 1 :(得分:1)
您可以使用Array.prototype.map
执行此操作。
<强> ES6 强>
...
objectArray: group.users.map((user) => ({ user, value: 1 }))
...
<强> ES5 强>
...
objectArray: group.users.map(function (user) {
return {
user: user,
value: 1
};
})
...