I want to convert this data
var data = [{
"Country": "World",
"Source": "Electricity",
"Year": "2022",
"Value": "20.0000"
},
{
"Country": "World",
"Source": "Gas",
"Year": "2022",
"Value": "30.0000"
},
{
"Country": "World",
"Source": "Hydrogen",
"Year": "2022",
"Value": "40.0000"
},
{
"Country": "World",
"Source": "Oil",
"Year": "2022",
"Value": "50.0000"
},
{
"Country": "World",
"Source": "Renewables",
"Year": "2022",
"Value": "60.0000"
},{
"Country": "World",
"Source": "Renewables",
"Year": "2021",
"Value": "50.0000"
}
];
to this format
[{
name: 'Renewables',
data: [60.0000, 50.0000]
}, {
name: 'Oil',
data: [50.0000]
},{
name: 'Hydrogen',
data: [40.0000]
}, {
name: 'Gas',
data: [30.0000]
}, {
name: 'Electricity',
data: [20.0000]
}]
how can I do that?
Any Suggestion please
Code I have done
for (let index = 0; index < uniqueSources.length; index ) {
var arrSmall = [];
for (let j = 0; j < this.ResponseToShow.length; j ) {
if (uniqueSources[index] == this.ResponseToShow[j]['Source']) {
arrSmall.push(Number(this.ResponseToShow[j]['Value']));
}
}
}
console.log(arrSmall);
CodePudding user response:
Common use case of reduce
var data = [{
"Country": "World",
"Source": "Electricity",
"Year": "2022",
"Value": "20.0000"
},
{
"Country": "World",
"Source": "Gas",
"Year": "2022",
"Value": "30.0000"
},
{
"Country": "World",
"Source": "Hydrogen",
"Year": "2022",
"Value": "40.0000"
},
{
"Country": "World",
"Source": "Oil",
"Year": "2022",
"Value": "50.0000"
},
{
"Country": "World",
"Source": "Renewables",
"Year": "2022",
"Value": "60.0000"
},{
"Country": "World",
"Source": "Renewables",
"Year": "2021",
"Value": "50.0000"
}
];
let res = Object.values(data.reduce((acc,curr) => {
if(!acc[curr.Source]){
acc[curr.Source] = {name: curr.Source,data: []}
}
acc[curr.Source]['data'].push(curr.Value)
return acc;
},{}))
console.log(res)
CodePudding user response:
You can use .forEach()
, .findIndex()
and .reverse()
to achieve this. Try this
var data = [
{
"Country": "World",
"Source": "Electricity",
"Year": "2022",
"Value": "20.0000"
},
{
"Country": "World",
"Source": "Gas",
"Year": "2022",
"Value": "30.0000"
},
{
"Country": "World",
"Source": "Hydrogen",
"Year": "2022",
"Value": "40.0000"
},
{
"Country": "World",
"Source": "Oil",
"Year": "2022",
"Value": "50.0000"
},
{
"Country": "World",
"Source": "Renewables",
"Year": "2022",
"Value": "60.0000"
},{
"Country": "World",
"Source": "Renewables",
"Year": "2021",
"Value": "50.0000"
}
];
let fdata = []; // formatted data
data.forEach(({Source, Value}) => {
let index = fdata.findIndex(o => o.name === Source); // check if Source exist
if( index === -1 ){
fdata.push({name: Source, data: [Value]});
}else{
fdata[index].data.push(Value);
}
});
fdata = fdata.reverse(); // to reverse the order
console.log(fdata)