Home > OS >  Map multiple values to different variables
Map multiple values to different variables

Time:07-07

const x = failedCo2Quantities.map((i) => i.ITEMID);

const y = failedCo2Quantities.map((i) => i.PRODUCTID);

const z = failedCo2Quantities.map((i) => i.PLANTID);

Is it possible to use a single map function for this?

CodePudding user response:

map is often used for creating a new array based on another array. Altough you can use it without getting its array result, but it is not recommended (see here).

let obj = {ITEMID:[], PRODUCTID:[], PLANTID:[]}; 
failedCo2Quantities.map(i => {
    obj.ITEMID.push(i.ITEMID);
    obj.PRODUCTID.push(i.PRODUCTID);
    obj.PLANTID.push(i.PLANTID);
    return;
});

Since in this case you don't want any returning value, I think forEach is better.

let obj = {ITEMID:[], PRODUCTID:[], PLANTID:[]}; 
failedCo2Quantities.forEach(i => {
    obj.ITEMID.push(i.ITEMID);
    obj.PRODUCTID.push(i.PRODUCTID);
    obj.PLANTID.push(i.PLANTID);
});

CodePudding user response:

As an alternative you can use the reduce function.

failedCo2Quantities.reduce((acc, current) => {
   acc.ITEMID.push(current.ITEMID);
   acc.PRODUCTID.push(current.PRODUCTID);
   acc.PLANTID.push(current.PLANTID);
   return acc;
}, {ITEMID:[], PRODUCTID:[], PLANTID:[]})
  • Related