我有下面的对象数组
var testdata = [{
TYPE: 'type 1', Category: 'Booking', Count : 5
},
{
TYPE: 'type 2', Category: 'Booking', Count : 15
},
{
TYPE: 'type 1', Category: 'Planning', Count : 10
},
{
TYPE: 'type 3', Category: 'SALES', Count : 5
}]
我想对每个类别进行分组,然后按类型和计数,如下所示:
var resultdata =
{
"Booking": {
"type 1": 5,
"type 2": 15
},
"Planning": {
"type 1": 10
},
"SALES": {
"type 3": 5
},
}
到目前为止,我已经写了下面的逻辑,但它没有给我预期的结果,它只是添加每个类别的最后一个值
$.each(testdata , function (key, value) {
if(value.Category == "Booking"){
bookingarray['Booking'] = {[value.TYPE]: value.Count}
}
})
你可以尝试这样做:
$.each(testdata, function(key, value) {
if (!bookingarray[value.Category]) {
bookingarray[value.Category] = {} // if example "Booking" does not exist in resultData, then create it
}
bookingarray[value.Category][value.TYPE] = value.Count
})
var testdata = [{
TYPE: 'type 1',
Category: 'Booking',
Count: 5
},
{
TYPE: 'type 2',
Category: 'Booking',
Count: 15
},
{
TYPE: 'type 1',
Category: 'Planning',
Count: 10
},
{
TYPE: 'type 3',
Category: 'SALES',
Count: 5
}
]
var bookingarray = {};
$.each(testdata, function(key, value) {
if (!bookingarray[value.Category]) {
bookingarray[value.Category] = {}
}
bookingarray[value.Category][value.TYPE] = value.Count
})
console.log(bookingarray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
const testdata = [
{
TYPE: 'type 1', Category: 'Booking', Count : 5
}, {
TYPE: 'type 2', Category: 'Booking', Count : 15
}, {
TYPE: 'type 1', Category: 'Planning', Count : 10
}, {
TYPE: 'type 3', Category: 'SALES', Count : 5
}
];
let categories = new Set(testdata.map(t => t.Category));
let resultData = {};
categories.forEach(c => testdata.map(t => {
if (t.Category === c) {
if(resultData[c]) resultData [c][t.TYPE] = t.Count;
else resultData = { ...resultData , [c]: { [t.TYPE]: t.Count } };
}
}));
console.log(resultData);