简体   繁体   English

创建地图以减少。 使用Javascript

[英]Create Map to reduce. Javascript

I have a result of "ImputacionData", and with a reduces it I group it with an attribute of the object: 我有一个“ImputacionData”的结果,并且通过减少它我将它与对象的属性组合在一起:

this.imputacionesDatas = data;
this.imputacionesAndAusencias = this.imputacionesDatas.reduce(function (r, a) {
        r[a.empleadoId] = r[a.empleadoId] || [];
        r[a.empleadoId].push(a);
        return r;
    }, Object.create(null));

The problem that I do not know how to work with the result, would need to put it in a Map to be able to work with that data on the screen and be able to paint them. 我不知道如何处理结果的问题需要将它放在Map中才能在屏幕上处理这些数据并能够绘制它们。

I do not know how to put the result of the "reduce" in something like: 我不知道如何把“减少”的结果放在:

Map <number, Array <ImputacionData >>;

You could take Object.entries for getting keys and values in an array. 您可以使用Object.entries获取数组中的键和值。

this.imputacionesAndAusencias = Object.entries(this.imputacionesDatas.reduce(function (r, a) {
    r[a.empleadoId] = r[a.empleadoId] || [];
    r[a.empleadoId].push(a);
    return r;
}, Object.create(null)));

If you like to get a Map , you could take the map as return value. 如果您想获得Map ,可以将地图作为返回值。

this.imputacionesAndAusencias = this.imputacionesDatas.reduce(function (map, object) {
    if (!map.has(object.empleadoId)) {
        return map.set(object.empleadoId, [object]);
    }
    map.get(object.empleadoId).push(object);
    return map;
}, new Map);

You can set the accumulator's initial value to new Map() and then use the Map methods to set its values. 您可以将累加器的初始值设置为new Map() ,然后使用Map方法设置其值。

 const input = [{ empleadoId: 5 }, { empleadoId: 5 }, { empleadoId: 6 }]; const output = input.reduce((map, item) => { const { empleadoId } = item; if (map.has(empleadoId)) map.get(empleadoId).push(item); else map.set(empleadoId, [item]); return map; }, new Map()); console.log(...output); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM