gpt4 book ai didi

javascript - 循环 JSON 对象并将唯一的 JSON 项分配给给定变量

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:24 25 4
gpt4 key购买 nike

我正在构建一个作品集,我想要构建的一个项目类似于 AirTasker

我目前正在开发在 node.js 中构建的 API,它接受一个 JSON 对象,这个 JSON 对象基本上是正在请求的任务,需要由它分配的相关人员完成,目前它是自动分配的。

这是我的测试虚拟数据:

[
{
"clientId": 1,
"requestId": "help move bed",
"hours": 6
},
{
"clientId": 2,
"requestId": "pickup parcel",
"hours": 1
},
{
"clientId": 1,
"requestId": "cut the grass",
"hours": 4
},
{
"clientId": 1,
"requestId": "clean the kitchen",
"hours": 2
}
]

现在我的 API 目前的结构如下:

var workers = [
{"id": 1, "name": "Person 1", "tasks": []},
{"id": 2, "name": "Person 2", "tasks": []},
{"id": 3, "name": "Person 3", "tasks": []},
{"id": 4, "name": "Person 4", "tasks": []},
{"id": 5, "name": "Person 5", "tasks": []},
{"id": 6, "name": "Person 6", "tasks": []},
]


app.post('/api/v1/request', (req, res) => {

var requestData = req.body;

// Loop the tasks passed in
requestData.forEach(request => {


// Now evenly spread tasks across workers
workers.forEach(p => {

workers.tasks.push(request);

})

console.log(request);
});

res.status(200).send({
success: 'true',
message: 'Tasks has been assigned.',
workers: workers
})
});

对象workers作为将执行任务的人,我遇到的问题是当我循环requestData时,我无法弄清楚为每个 worker 分配一项任务的语法,目前我的代码是如何将一项任务分配给所有 worker 并继续,最终结果将是所有 worker 都拥有相同的任务。

有人可以帮助我如何为每个 worker 分配一项独特的任务

最佳答案

const workers = [
{"id": 1, "name": "Person 1", "tasks": []},
{"id": 2, "name": "Person 2", "tasks": []},
{"id": 3, "name": "Person 3", "tasks": []},
{"id": 4, "name": "Person 4", "tasks": []},
{"id": 5, "name": "Person 5", "tasks": []},
{"id": 6, "name": "Person 6", "tasks": []},
]

const dummies = [
{
"clientId": 1,
"requestId": "help move bed",
"hours": 6
},
{
"clientId": 2,
"requestId": "pickup parcel",
"hours": 1
},
{
"clientId": 1,
"requestId": "cut the grass",
"hours": 4
},
{
"clientId": 1,
"requestId": "clean the kitchen",
"hours": 2
}
];

workers.forEach(w => {
w.tasks = dummies.filter(d => d.clientId === w.id);
});

console.log(workers);

尝试这个简单的代码。

关于javascript - 循环 JSON 对象并将唯一的 JSON 项分配给给定变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53409833/

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