如何编写适当的函数以将Calendar_ID忙碌数组从响应匹配到客户端日历数组项?
这是我从服务器收到的代码:
初始化对象nr 1
response = {
calendars: {
calendarID_1: {
busy: [{},{}]
},
calendarID_2: {
busy: [{},{}]
},
},
...
}
这是我需要合并数据的代码:
初始化arr nr 2
clients = [
{
name: clientName,
calendars: ["calendarID_1", "calendarID_2"]
},
...
]
这是迭代函数之后的样子:
输出arr应该是
clients = [
{
name: clientName,
calendars: {
calendarID_1: {
busy: [{}, {}]
},
calendarID_2: {
busy: [{}, {}]
},
}
},
...
]
我的尝试是:
for (const calendar in response.calendars) {
for (const client in clients) {
clients[client].calendars.reduce((acc, cur) => {
if (cur === calendar) {
acc[cur] = response.calendars[calendar];
}
});
}
}
答案 0 :(得分:0)
// Input:
const response = {
calendars: {
calendarID_1: {
content: "of calendar 1",
},
calendarID_2: {
content: "of calendar 2",
},
calendarID_3: {
content: "of calendar 3",
},
},
}
const clients = [
{
name: "first",
calendars: ["calendarID_1", "calendarID_2"]
},
{
name: "second",
calendars: ["calendarID_3"]
},
]
// Solution:
const result = clients.map(client => ({
...client,
calendars: Object.fromEntries(
client.calendars.map(id => ([ id, response.calendars[id] ]))
),
}));
console.log(result);
这将映射到一个新的客户端数组,传播先前的客户端,该客户端基本上会浅抄整个数组,然后获取客户端日历的ID,在响应中查找它们,并从中创建一个新对象。这是客户日历ID的数量的O(n)。