angular - 如何将数组的值转换为筛选后的数组
我有这个问题,我使用的是 Angular 8,我希望你能帮我,我已经很长时间无法解决它了。
我有这个数组:
datos = [{
Description: 'Puede Insertar',
Id: 1,
Type: 'ADMON',
Value: '1'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'ADMON',
Value: '2'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'ADMON',
Value: '3'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'USER',
Value: '1'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'USER',
Value: '2'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'USER',
Value: '4'
},
]
我需要像这样筛选和分组它们:
result = [
{ADMON: {0: 1,
1: 2,
2: 3,
3: 4}},
{USER: {0: 1,
1: 2,
2: 4}}
];
我尝试了很多方法但我做不到,我希望你能帮我,非常感谢你提前的帮助。
答案#1
这里有一个潜在的解决方案,使用多种数组方法来完成手头的任务。
const datos = [{
Description: 'Puede Insertar',
Id: 1,
Type: 'ADMON',
Value: '1'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'ADMON',
Value: '2'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'ADMON',
Value: '3'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'USER',
Value: '1'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'USER',
Value: '2'
},
{
Description: 'Puede Insertar',
Id: 1,
Type: 'USER',
Value: '4'
}
];
const grouped = datos.reduce((acc, el) => {
if (!acc[el.Type]) acc[el.Type] = {};
const index = Object.values(acc[el.Type]).length;
acc[el.Type] = {
...acc[el.Type],
[index]: el.Value
}
return acc;
}, {});
const final = Object.entries(grouped).map(([key, val]) => {
return { [key]: val }
});
console.log(final);答案#2
const datos = [{Description:'Puede Insertar',Id:1,Type:'ADMON',Value:'1'},{Description:'Puede Insertar',Id:1,Type:'ADMON',Value:'2'},{Description:'Puede Insertar',Id:1,Type:'ADMON',Value:'3'},{Description:'Puede Insertar',Id:1,Type:'USER',Value:'1'},{Description:'Puede Insertar',Id:1,Type:'USER',Value:'2'},{Description:'Puede Insertar',Id:1,Type:'USER',Value:'4'}];
let result = Object.entries(datos.reduce((acc, {Type, Value}) => {
(acc[Type] = acc[Type] || []).push(Value);
return acc;
}, {}))
.map((o) => { return {[o[0]]: {...o[1]}}});
console.log(result);