sorry if the title is a bit missleading, I new to js so idk how to explain what I want to do properly so I'm gonna show my code and what I expect instead.
so I have this array of objects
const mi_array = [{
text: "1st title",
col2015: 81.8,
col2016: 86.4,
col2017: 67.3,
col2018: 70.8,
col2019: 67.6
},{
text: "2nd title",
col2015: 90.8,
col2016: 67.4,
col2017: 39.3,
col2018: 50.8,
col2019: 95.6
}];
I need something like this
const new_array = [{
name: "1st title",
data: [81.8,86.4,67.3,70.8,67.6]
},{
name: "2nd title",
data: [90.8,67.4,39.3,50.8,95.6]
}];
I've been searching on how to do it but this is all I found so far and it comes close to what I need but not quite there yet
const new_array = [];
mi_array.forEach(value => {
for (let key in value) {
new_array.push(value[key]);
}
});
console.log(new_array);
But my output it's this
["1st title", 81.8, 86.4, 67.3, 70.8, 67.6, "2nd title", 90.8, 67.4, 39.3, 50.8, 95.6];
CodePudding user response:
You can map
through the array and create a new object, where the data
property is the numeric property values of the original.
const mi_array=[{text:"1st title",col2015:81.8,col2016:86.4,col2017:67.3,col2018:70.8,col2019:67.6},{text:"2nd title",col2015:90.8,col2016:67.4,col2017:39.3,col2018:50.8,col2019:95.6}];
const result = mi_array.map(e => ({
name: e.text,
data: Object.values(e).filter(e => typeof e == 'number')
}))
console.log(result)