I have an array of objects I need transformed into an array of new objects. Is there a way this can be done without manually defining "texas" or "california" when defining the new array of objects?
This is my original data:
const data = [
{
year: "2005",
texas: 6.984323232343243
},
{
year: "2006",
texas: 8.507629970573532
},
{
year: "2005",
california: 8.422823214889691
},
{
year: "2006",
california: 9.456857576876532
}
];
And I need it to look like this:
const newData = [
{
year: 2005,
texas: 6.984323232343243,
california: 8.422823214889691
},
{
year: 2006,
texas: 8.507629970573532,
california: 9.456857576876532
}
];
I’ve attempted to group these objects and then ungroup, but I’ve only been able to group and can’t seem to figure out how to ungroup it the way I need. Is there a way I can do this without grouping it first?
const data = [
{
year: "2005",
texas: 6.984323232343243
},
{
year: "2006",
texas: 8.507629970573532
},
{
year: "2005",
california: 8.422823214889691
},
{
year: "2006",
california: 9.456857576876532
}
];
const groupByReduce = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
)
return result
}, {});
};
const newData = groupByReduce(data, "year");
console.log(newData);
.as-console-wrapper { max-height: 100% !important; top: 0; }