[英]How to match array elements from one object into another object?
如何編寫適當的函數以將Calendar_ID繁忙數組從響應匹配到客戶端日歷數組項?
這是我從服務器收到的代碼:
初始化對象nr 1
response = {
calendars: {
calendarID_1: {
busy: [{},{}]
},
calendarID_2: {
busy: [{},{}]
},
},
...
}
這是我需要合並數據的代碼:
初始化錯誤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];
}
});
}
}
// 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)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.