ウェブサイト検索

TypeScript - Angular 2 - 結合


私は二つのオブジェクトを持っています - 時間と顧客です。

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

両方のオブジェクトに customer_id フィールドがあります。今、hour リストの詳細と customer リストの customer_name を組み合わせた新しいリストを作成したいです。

this.hourswithcustomers[] = ?

これらの2つのオブジェクト/リストを新しいリストに結合して、次の結果を得るにはどうすればよいですか?

| 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 で顧客を見つけるメソッドです。私はあなたのコードを知らないので、あなたがどのようにそれを見つけるかを考えることはできません。