Torben Torben - 3 months ago 6
JSON Question

Prepare JSON data on basis of JSON and array - JavaScript

I have a JSON file with the following structure:

{ ShippingDate: '06.09.2016',
'Order ID': 200003946,
ID: 751,
Product: 'Mobile Phone'},
{ ShippingDate: '06.09.2016',
'Order ID': 200003946,
ID: 751,
Product: 'TV'},
{ ShippingDate: '06.09.2016',
'Order ID': 200003946,
ID: 751,
Product: 'Batteries'},
{ ShippingDate: '06.09.2016',
'Order ID': 200003926,
ID: 752,
Product: 'Car'},


So the first three entries are an order of the same customer. The fourth one is an order of another customer.

I know want to use a handlebars.js template to create an html file with each order including the items the order has. So I prepared this template:

<div class="header">
<h1>{{ID}}</h1>
</div>
<div class="body">
<ul>
{{#each Product}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>


I now have the problem, that I need to prepare that kind of data for the template. And here I stumbled across some problems. My code goes like this

...
var f = fs.readFileSync('data.json').toString();
var lines = JSON.parse(f);
var items = [];
//prepare products of one customer and put them into an array
for (var key in lines) {

var line = lines[key];
var nextLine = lines[(parseInt(key)+1)];

if (nextLine !== undefined && line !== undefined) {
if (line['Order ID'] !== nextLine['Order ID']) {
items.push('Product: ' + line.Product);
}//if
}//if
}//for

var data = lines;
fs.readFile(template.html, 'utf-8', function(error, source){
var template = handlebars.compile(source);
var html = template(data);
console.log(html)
});


This is not working - how can I prepare my array of items so that I can access these products with the products variable in my template? Additionally I need to add information like ID and Shipping Date to that json string. The data format must look like this:

var data = {
ShippingDate: '06.09.2016',
ID: '751',
Product: ['Mobile Phone', 'TV', 'Batteries']
}


Anybody can help here?

Answer

Here is a way to do it :

var data = [{
    "ShippingDate": "06.09.2016",
    "Order ID": 200003946,
    "ID": 751,
    "Product": "Mobile Phone"
}, {
    "ShippingDate": "06.09.2016",
    "Order ID": 200003946,
    "ID": 751,
    "Product": "TV"
}, {
    "ShippingDate": "06.09.2016",
    "Order ID": 200003946,
    "ID": 751,
    "Product": "Batteries"
}, {
    "ShippingDate": "06.09.2016",
    "Order ID": 200003926,
    "ID": 752,
    "Product": "Car"
}];

var newData = {};

data.forEach(function(item) {
    if (typeof newData[item.ID] === 'undefined') {
        newData[item.ID] = {
            ShippingDate: item.ShippingDate,
            ID: item.ID,
            Product: []
        };
    }

    newData[item.ID].Product.push(item.Product);
});

newData = Object.values(newData);