Reputation: 139
I have a JSON file that comes in a particular structure (see Sample A), but I need it too be structured like Sample B.
Is it possible to reorganise the data in JS? If so, how do you go about this?
Sample A:
var myData = [
{
"date": "01/01/2017",
"here-value": "20",
"here-color": "pink",
"there-value": "24",
"there-color": "red",
},
{
"date": "02/01/2017",
"here-value": "80",
"here-color": "blue",
"there-value": "54",
"there-color": "red",
},
]
Sample B:
var myData = [
{
"date": "01/01/2017",
"here-value": "20",
"here-color": "pink"
},
{
"date": "01/01/2017",
"there-value": "24",
"there-color": "red"
},
{
"date": "02/01/2017",
"here-value": "80",
"here-color": "blue"
},
{
"date": "02/01/2017",
"there-value": "54",
"there-color": "red"
}
]
The reason I'm seeking to restructure the data, is to create objects that will feed into a visualisation using D3. The result will be similar to: http://jsfiddle.net/vw88/nzwLg96a/
Upvotes: 0
Views: 3171
Reputation: 148
var myData = [{
"date": "01/01/2017",
"here-value": "20",
"here-color": "pink",
"there-value": "24",
"there-color": "red",
},
{
"date": "02/01/2017",
"here-value": "80",
"here-color": "blue",
"there-value": "54",
"there-color": "red",
},
]
var newData = []
myData.forEach(b => {
newData.push({
date: b.date,
"here-value": b["here-value"],
"here-color": b["here-color"],
}, {
date: b.date,
"there-value": b["there-value"],
"there-color": b["there-color"],
})
});
console.log(newData);
Upvotes: 1
Reputation: 887
Thought I would include this approach as-well using Array.reduce()
let restructuredData = myData.reduce((a, b) => {
return a.concat([
{ "date": b["date"], "here-value": b["here-value"], "here-color": b["here-color"] },
{ "date": b["date"], "there-value": b["there-value"], "there-color": b["there-color"] }
]);
}, []);
Upvotes: 4
Reputation: 247
This also working,
var myData = [
{
"date": "01/01/2017",
"here-value": "20",
"here-color": "pink",
"there-value": "24",
"there-color": "red",
},
{
"date": "02/01/2017",
"here-value": "80",
"here-color": "blue",
"there-value": "54",
"there-color": "red",
},
] ;
var newAr = [];
myData.forEach(function(val, key){
newAr.push({"date": val.date, "here-value": val["here-value"],
"here-color": val["here-color"]});
newAr.push({"date": val.date, "there-value": val["there-value"],
"there-color": val["there-color"]});
})
console.log("newAr:", newAr);
Upvotes: 1
Reputation: 127
This should do the trick:
var sampleA = [
{
"date": "01/01/2017",
"here-value": "20",
"here-color": "pink",
"there-value": "24",
"there-color": "red",
},
{
"date": "02/01/2017",
"here-value": "80",
"here-color": "blue",
"there-value": "54",
"there-color": "red",
},
]
var sampleB = [];
sampleA.forEach( i => {
let a = {};
a.date = i.date;
a['here-value'] = i['here-value'];
a['here-color'] = i['here-color'];
let b = {};
b.date = i.date;
b['there-value'] = i['there-value'];
b['there-color'] = i['there-color'];
sampleB.push(a, b);
});
console.log(sampleB);
Upvotes: 1