将对象组合在一起

时间:2014-02-12 10:26:29

标签: javascript

{"data":[{"Part_Number":"PT_1029"},{"Part_Name":"Real-Time Clock (RTC)"},
         {"Quantity_Failed":2},{"Depot_Location":"WarehouseCAL"},
         {"Distance_miles":5},{"Quantity_Available":7},{"Unit_Price":75},
         {"Delivery_Cost":5.5},{"Applicable_Discount":100},
         {"Part_Number":"PT_1030"},{"Part_Name":"Safety Processor"},
         {"Quantity_Failed":1},{"Depot_Location":"WarehouseCAL"},
         {"Distance_miles":2},{"Quantity_Available":8},{"Unit_Price":85},
         {"Delivery_Cost":2.5},{"Applicable_Discount":100},
         {"Part_Number":"PT_1036"},{"Part_Name":"Sensors"},{"Quantity_Failed":3},
         {"Depot_Location":"WarehouseCAL"},{"Distance_miles":3},
         {"Quantity_Available":6},{"Unit_Price":45},{"Delivery_Cost":3.5},
         {"Applicable_Discount":100}]}

到下面的一些事情:

{"data":[{"Part_Number":"PT_1029","Part_Name":"Real-Time Clock (RTC)",
          "Quantity_Failed":2,"Depot_Location":"WarehouseCAL","Distance_miles":5,
          "Quantity_Available":7,"Unit_Price":75,"Delivery_Cost":5.5,
          "Applicable_Discount":100},
         {"Part_Number":"PT_1030","Part_Name":"Safety Processor",
          "Quantity_Failed":1,"Depot_Location":"WarehouseCAL","Distance_miles":2,
          "Quantity_Available":8,{"Unit_Price":85,"Delivery_Cost":2.5,
          "Applicable_Discount":100},
         {"Part_Number":"PT_1036","Part_Name":"Sensors",
          "Quantity_Failed":3,"Depot_Location":"WarehouseCAL",
          "Distance_miles":3,"Quantity_Available":6,"Unit_Price":45,
          "Delivery_Cost":3.5,"Applicable_Discount":100}]}

2 个答案:

答案 0 :(得分:2)

res = {data:[]}

obj.data.forEach(function(x) {
    if(x.Part_Number)
        res.data.push({});
    Object.keys(x).forEach(function(k) {
        res.data[res.data.length - 1][k] = x[k];
    });
});
顺便说一下,你的问题与JSON无关。 JSON是 strings 的格式,您的代码段是javascript对象。这是一个很常见的错误,但仍然是一个错误。

答案 1 :(得分:0)

没有任何其他库(我确定有人会使用jQuery):

res=[];
t={};
res.push(t);
for (var i =0;i<obj.data.length;i++){
  var d = obj.data[i];
  for (var prop in d){ 
    if (t[prop]){  
      t={};
      res.push(t);
    }
    t[prop] = d[prop]; 
  }
}