i would need your help, after receiving the data this way from an api call:
response = [
{ area: "Z", val: "work", count: 12, data: "2022-03-01T00:00:00" },
{ area: "Z", val: "not work", count: 41, data: "2022-04-01T00:00:00" },
{ area: "R", val: "work", count: 55, data: "2022-03-01T00:00:00" },
{ area: "R", val: "not work", count: 62, data: "2022-04-01T00:00:00" }
];
i need a method to dynamically transform this object into:
[
{area:'Z',count:['03-2022':{'work':12},'04-2022':{'not work':41}]},
{area:'R',count:['03-2022':{'work':55},'04-2022':{'not work':62}]]}
]
Thank you
CodePudding user response:
since your count
is not valid syntax. i assumed it is an array of objects.
These grouping problems are easily solvable using reduce
const response = [{ area: "Z", val: "work", count: 12, data: "2022-03-01T00:00:00" },{ area: "Z", val: "not work", count: 41, data: "2022-04-01T00:00:00" },{ area: "R", val: "work", count: 55, data: "2022-03-01T00:00:00" },{ area: "R", val: "not work", count: 62, data: "2022-04-01T00:00:00" }];
const res = Object.values(response.reduce((acc,{area,val,count,data}) => {
if(!acc[area])acc[area]={area: area, count:[]}
acc[area]['count'].push({[data.substring(0,7)] : {[val]:count}})
return acc
},{}))
console.log(res)
CodePudding user response:
If you are open to use lodash or underscore, here is a solution:
const response = [{
area: "Z",
val: "work",
count: 12,
data: "2022-03-01T00:00:00"
},
{
area: "Z",
val: "not work",
count: 41,
data: "2022-04-01T00:00:00"
},
{
area: "R",
val: "work",
count: 55,
data: "2022-03-01T00:00:00"
},
{
area: "R",
val: "not work",
count: 62,
data: "2022-04-01T00:00:00"
}
];
const group = _.groupBy(response, 'area');
const result = _.map(_.keys(group), i => {
return {
area: i,
count: _.map(group[i], j => {
return {
[j.data.substring(0, 7)]: {
[j.val]: j.count
}
}
})
}
})
console.log('result', result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
This is a plain JS solution.
const response = [{
area: "Z",
val: "work",
count: 12,
data: "2022-03-01T00:00:00"
},
{
area: "Z",
val: "not work",
count: 41,
data: "2022-04-01T00:00:00"
},
{
area: "R",
val: "work",
count: 55,
data: "2022-03-01T00:00:00"
},
{
area: "R",
val: "not work",
count: 62,
data: "2022-04-01T00:00:00"
}
];
const groupBy = (arr, key) => {
const initialValue = {};
return arr.reduce((acc, cval) => {
const myAttribute = cval[key];
acc[myAttribute] = [...(acc[myAttribute] || []), cval]
return acc;
}, initialValue);
};
const group = groupBy(response, 'area');
const result = Object.keys(group).map(i => {
return {
area: i,
count: group[i].map(j => {
return {
[j.data.substring(0, 7)]: {
[j.val]: j.count
}
}
})
}
})
console.log(result)