Quiero convertir estos datos
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" } ];a este formato
[{ 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] }]¿Cómo puedo hacer eso?
Cualquier sugerencia por favor
Código que he hecho
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);Caso de uso común de 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)Puede usar .forEach() , .findIndex() y .reverse() para lograr esto. Prueba esto
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)