1 回答

TA貢獻1877條經驗 獲得超6個贊
您可以創建所有不同值的 a,然后循環訪問 中的每個值,檢查它們是否具有所有不同的值,如果沒有,則推送具有該類型和度量的新對象:SettypepersonGroupedByColortype0
arr = [{
"date": "2020-01-01",
"metric": 32,
"type": "Google"
},
{
"date": "2020-01-01",
"metric": 24,
"type": "Bing"
},
{
"date": "2020-01-02",
"metric": 1,
"type": "Google"
},
{
"date": "2020-01-02",
"metric": 32,
"type": "Jeeves"
},
{
"date": "2020-01-03",
"metric": 24,
"type": "Bing"
},
{
"date": "2020-01-03",
"metric": 30,
"type": "Google"
}
]
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
return result;
}, {});
};
let personGroupedByColor = groupBy(arr, 'date');
const types = new Set(arr.map(a => a.type));
for (a in personGroupedByColor) {
types.forEach(t => {
if (!personGroupedByColor[a].some(v => v.type == t)) {
personGroupedByColor[a].push({
"date": personGroupedByColor[a][0].date,
"metric": 0,
"type": t
});
}
})
}
console.log(personGroupedByColor);
添加回答
舉報