gpt4 book ai didi

javascript - 将数组复制到另一个对象属性javascript

转载 作者:行者123 更新时间:2023-11-28 13:04:53 25 4
gpt4 key购买 nike

我有两个对象:

Group 具有 users 属性,包含 ObjectId 数组:

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

另一个对象有一个属性,需要用精确的 objectId 数组填充,所以当我在后面创建它时,它现在看起来像这样:

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} 或其他内容。我不明白如何在声明新对象时迭代该数组...

最佳答案

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

关于javascript - 将数组复制到另一个对象属性javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com