基于2个阵列创建对象阵列



我有一个数组,它看起来像这样。

const date = ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05']

我有一个对象数组,它看起来像这样。

const data = [
{
category: 'a',
date: '2021-01-01',
qty: '1'
},
{
category: 'a',
date: '2021-01-02',
qty: '2'
},
{
category: 'b',
date: '2021-01-02',
qty: '1'
},
{
category: 'b',
date: '2021-01-03',
qty: '2'
},
{
category: 'c',
date: '2021-01-03',
qty: '1'
},
{
category: 'c',
date: '2021-01-04',
qty: '2'
},
]

我希望结果是这样的,数据集的长度应该是5(基于日期的长度(。

[
{
label: 'a',
datasets: ['1', '2', '0', '0', '0']
},
{
label: 'b',
datasets: ['0', '1', '2', '0', '0']
},
{
label: 'c',
datasets: ['0', '0', '1', '2', '0']
},
]

我自己尝试了代码,但结果看起来像这个

[
{
label: 'a',
datasets: ['1', '2']
},
{
label: 'b',
datasets: ['1', '2']
},
{
label: 'c',
datasets: ['1', '2']
},
]

有人能帮我编码一下吗?

编辑

const data = [
{
category: 'a',
date: '2021-01-01',
qty: '1'
},
{
category: 'a',
date: '2021-01-02',
qty: '2'
},
{
category: 'b',
date: '2021-01-02',
qty: '1'
},
{
category: 'b',
date: '2021-01-03',
qty: '2'
},
{
category: 'c',
date: '2021-01-03',
qty: '1'
},
{
category: 'c',
date: '2021-01-04',
qty: '2'
},
];
var output = [];
data.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.label == item.category;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].datasets = output[existingIndex].datasets.concat(item.qty);
} else {
if (typeof item.qty == 'string') item.qty = [item.qty];
output.push({
label: item.category,
datasets: item.qty
});
}
});
console.log('Output', output);

看起来,您不尊重dat数组的长度,而只将push值作为组的datasets值。

为了克服这一点,您可以使用一个对象来获取日期的索引,并且对于未给定的datasets,将date映射为值零。

const
dates = ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
data = [{ category: 'a', date: '2021-01-01', qty: '1' }, { category: 'a', date: '2021-01-02', qty: '2' }, { category: 'b', date: '2021-01-02', qty: '1' }, { category: 'b', date: '2021-01-03', qty: '2' }, { category: 'c', date: '2021-01-03', qty: '1' }, { category: 'c', date: '2021-01-04', qty: '2' }],
indices = Object.fromEntries(dates.map((k, i) => [k, i])),
result = Object.values(data.reduce((groups, { category: label, date, qty }) => {
groups[label] ??= { label, datasets: Array.from(dates).fill('0') };
groups[label].datasets[indices[date]] = qty;
return groups;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新