2014-04-06 119 views
0

道歉這似乎是一個簡單的解決方案,但我對Node.js很陌生,並且努力想出答案。我有一個包含下令給定日期的所有項目的平面列表,看上去就像一個JSON文件(實際上是從SQL Server數據庫查詢的結果)以下節點JS Json解析

{ 
    "ProductName": "Product 1", 
    "OrderRef": "1010197", 
    "Country": "United States", 
    "Region": "Georgia", 
    "Postcode": "30318", 
    "PricePaid": 979, 
    "Currency": "GBP", 
    "Size": "42 IT", 
    "Colour": "Cream", 
    "OrderDate": "2014-04-03T06:06:31.000Z" 
}, { 
    "ProductName": "Product 2", 
    "OrderRef": "1010197", 
    "Country": "United States", 
    "Region": "Georgia", 
    "Postcode": "30318", 
    "PricePaid": 1295, 
    "Currency": "GBP", 
    "Size": "38 FR", 
    "Colour": "Green Black", 
    "OrderDate": "2014-04-03T06:06:31.000Z" 
}, { 
    "ProductName": "Product 1", 
    "OrderRef": "101019", 
    "Country": "United Kingdom", 
    "Region": "London", 
    "Postcode": "30318", 
    "PricePaid": 100, 
    "Currency": "GBP", 
    "Size": "38 FR", 
    "Colour": "Green Black", 
    "OrderDate": "2014-04-03T06:06:31.000Z" 
} 

我需要什麼,能夠做的是如下

[{ 
    "OrderRef": "123ABC", 
    "OrderDate": "2014-01-01", 
    "OrderTotal": 26.99, 
    "Region": "London", 
    "Country": "United Kingdom", 
    "Postcode": "W17FF", 
    "Items": [ 
     { 
     "Product": "A test product", 
     "Price": "12.99" 
     }, 
     { 
     "Product": "Another test product", 
     "Price": 14.99 
     } 
    ] 
    }, 
    { 
    "OrderRef": "ABC123", 
    "OrderDate": "2014-01-01", 
    "OrderTotal": 30.99, 
    "Region": "Hertfordshire", 
    "Country": "United Kingdom", 
    "Postcode": "ALX999", 
    "Items": [ 
     { 
     "Product": "A test product", 
     "Price": 12.99 
     }, 
     { 
     "Product": "Another test product", 
     "Price": 14.99 
     } 
    ] 
    } 

什麼是實現這一目標的最佳途徑,其中訂單組織改寫這個到一個新的JSON列表? 謝謝ossie

+0

這可以很容易地用簡單的循環和建立一個新的數組來實現。你有什麼嘗試? – badsyntax

+0

說實話,我已經花了大部分時間在Google上搜索並找到示例 – ossie

+0

是否有'OrderRef'保證您的訂單? –

回答

0

還有其他更好的方法可以做到這一點,但這種簡單的方法應該希望讓你明白如何以一般方式解決問題。可以應用相同的模式來創建小計。

var toConsolidate = [...]; // array of your items 
function reorganizeData(origArray){ 
    var currentKey = undefined; 
    var remappedRecord; 
    var remappedRecordArray = []; 
    for (var i = 0; i < origArray.length; i++){ 
     if (origArray[i].OrderRef !== currentKey) { 
      if(typeof currentKey !== 'undefined') 
       remappedRecordArray.push(remappedRecord); 
      remappedRecord = { 
       OrderRef: origArray[i].OrderRef, 
       Country: origArray[i].Country, 
       Items: [] 
      }; 
      currentKey =origArray[i].OrderRef; 
     } 
     remappedRecord.Items.push({ 
      Product: origArray[i].ProductName, 
      Price: origArray[i].PricePaid 
     }); 
    }; 
    remappedRecordArray.push(remappedRecord); 
    return remappedRecordArray; 
}; 

console.log(require('util').inspect(reorganizeData(toConsolidate), { depth: null })); 
+0

謝謝,今天晚些時候我會有一個遊戲 – ossie

+0

工作的魅力,謝謝 – ossie

+0

不客氣 - 很高興聽到它。 –