Null进入最终对象

时间:2017-02-18 14:12:30

标签: javascript json

如果它们具有相同的order_id,我正在聚合json对象orderData。在最终对象中,ordernewdata null在它的第二个索引处。在新数组中推送一个空对象。我错过了什么?

var ordersData={
  "orders":[
    {
      "order_id": 1,
      "user_id": 294,
      "amount": 500,
      "discount": 100,
      "created_at": "2016-11-07T07:36:46.000Z",
      "item_name": "Veg Manchurian Dry",
      "item_id": 1
    },
    {
      "order_id": 1,
      "user_id": 294,
      "amount": 500,
      "discount": 100,
      "created_at": "2016-11-07T07:36:46.000Z",
      "item_name": "Veg Chopsuey",
      "item_id": 2
    },
      {
      "order_id": 2,
      "user_id": 294,
      "amount": 500,
      "discount": 100,
      "created_at": "2016-11-07T07:38:42.000Z",
      "item_name": "Veg Chopsuey",
      "item_id": 2
    },


  ]
}

  var ordersnewdata ={
    "orders":[
    {
      "order_id": 1,
      "user_id": 1,
      "amount": 1,
      "discount": 1,
      "created_at": "",
      "items":[]
    }
    ]
  };


      var i=0;  
     for(k=i+1;k<ordersData.orders.length;k++){

        if(ordersData.orders[i].order_id==ordersData.orders[k].order_id){
          var item_name = ordersData.orders[k].item_name;
          var item_id   = ordersData.orders[k].item_id;
          var obj       = {item_name:item_name,item_id:item_id};
          ordersnewdata.orders[i].items.push(obj);                
       }

     else{

      var orders={
        order_id    : ordersData.orders[k].order_id,
        user_id     : ordersData.orders[k].user_id,
        amount      : ordersData.orders[k].amount_id,
        discount    : ordersData.orders[k].discount_id,
        created_at  : ordersData.orders[k].created_at,
        items       : {item_name:ordersData.orders[k].item_name,item_id:ordersData.orders[k].item_id},
      };    
      ordersnewdata.orders[k]=orders;
     }

   }


console.log(JSON.stringify(ordersnewdata));

1 个答案:

答案 0 :(得分:0)

在你的for循环中,

k = 1 时,它进入if语句。当 k = 2 时,它会进入 else 分支,换句话说,ordersnewdata.orders[2] = orders适用于您的情况。所以我们忘记评估ordersnewdata.orders[1]。这就是为什么null中会有ordernewdata.orders的原因。

要阻止添加null,您可以使用ordersnewdata.orders.push(orders)插入新订单。