2017-01-27 1 views
0

私はここでリクエストボディreq.bodyからオブジェクトの配列内のアイテムを反復する方法は?

 var orderItem = { 
      userPurchased: body.userPurchased, 
      products:[{ 
       product: body.products.product, 
       size: body.products.size, 
       quantity: body.products.quantity, 
       subTotal: body.products.subTotal 
      }], 
      totalQuantity: body.totalQuantity, 
      totalPrice: body.totalPrice, 
      otherShipAd: body.otherShipAd, 
      modeOfPayment: body.modeOfPayment 
     }; 

を使用して埋めるために必要な、この変数を持っているが、私のリクエストボディがどのように見えるです。

enter image description here

ここでの問題は、リクエストボディは、オブジェクトの配列であると私は私が上に示した方法でそれをアクセスする場合、それは未定義になることです。 body.products.product [0]のような配列の番号を置くと、すべてのレコードが同じになります。

誰も私にどの製品を反復して変数に入れるか教えてもらえますか?

答えて

1

わからない私はあなたのジレンマがあなたの先のオブジェクトがまったく同じを持っているように見えるという事実からではなく、何であるか理解してしまった場合スキーマをソースとして使用すると、その値を自分のvarに割り当てるのはなぜですか?

var orderItem = request.body; 

ここで、request.bodyから配列のコピーを作成する必要があるとします。これは依然としてrequest.body配列をターゲット変数に割り当てる1ライナーに過ぎません。

var orderItem = { 
     userPurchased: body.userPurchased, 
     products: body.products, 
     totalQuantity: body.totalQuantity, 
     totalPrice: body.totalPrice, 
     otherShipAd: body.otherShipAd, 
     modeOfPayment: body.modeOfPayment 
    }; 
+0

ありがとうございます。たぶん私は思っているだけかもしれない。 Agggghhh。悪い私。 –

0

コンソールの応答に応じて

あなたが使用する必要があります。

var product; 
    for(var i=0; i< body.products.length;i++) 
    { product = []; 
     product[product] =body.products[i].product[0]; 
    // set all properties 
    } 
    orderItem.products.push(product); 
関連する問題