道歉这似乎是一个简单的解决方案,但我对Node.js很新,并努力想出答案。我有一个JSON文件(实际上是SQL Server数据库查询的结果),其中包含为给定日期排序的所有项目的平面列表,如下所示
{
"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"
}
我需要做的是将其重写为新的JSON列表,其中订单分组如下
[{
"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
}
]
}
实现这一目标的最佳方法是什么? 谢谢ossie
答案 0 :(得分: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 }));