網站搜尋

TypeScript - Angular 2 - 連接


我有兩個對象——小時和顧客。

this.customer = Customers[]
this.hour = Hours[]

在這兩個對象中,我都有 customer_id 欄位——現在我想創建一個新清單,將小時清單的詳細資訊與客戶清單的 customer_name 結合起來。

this.hourswithcustomers[] = ?

我如何將這兩個物件/列表合併成一個新列表,以得到以下結果?

| hour.hour_id | hour.hour_amount | hour.customer_id | customer.customer_name |
| 1            | 500.00           | 99               | microsoft              |
| 2            | 300.00           | 55               | apple                  |
| 3            | 200.00           | 99               | microsoft              |

答案#1

合併這兩者最簡單的方法是結合一個 customerId -> Customer 的地圖。然後從那裡,你可以遍歷這些小時來填充 hourswithcustomers 物件。

資料映射:

var customerMap = {};
this.customer.forEach((customer) => {
    customerMap[customer.customer_id] = customer;
})

this.hourswithcustomers = this.hour.map((hour) => {
     return {
         hour: hour,
         customer: customerMap[hour.customer_id]
     };
});

在你的視圖中,你可以這樣顯示它:

<tr *ngFor="let hwc of hourswithcustomers">
    <td>{{hwc.hour.hour_id}}</td>
    <td>{{hwc.hour.hour_amount }}</td>
    <td>{{hwc.hour.customer_id}}</td>
    <td>{{hwc.customer.customer_name}}</td>
</tr>

答案#2

我不確定這是否可行,但可以試試這個:

 <tr *ngFor="let h of hourswithcustomer">
    <td > {{h.hour.hour_id}}</td>
    <td > {{h.hour.hour_amount }}</td>
    <td > {{h.customer.customer_id}}</td>
    <td > {{h.customer.customer_customername}}</td>
</tr>


this.hourswithcustomers = this.hours.map( hour => { 
    return {hour, customer: this.find(c.customerId)}
});

其中 find() 是用來尋找具有該 id 的客戶的方法。我不知道你的程式碼,我無法憑空想出你如何找到它的方式。