Skip to content Skip to sidebar Skip to footer

How To Display The Quantity Based On The Size

data=[{ color: 'red', qty: '0', _1x: '0', _2x: '0', _3x: '0', _4x: '0', xxs: '0', xs: '0', s: '14', m: '0', l:

Solution 1:

First filter for each color items = data.filter(t => t.color == result1[i].color); then you need to filter it by each size (_2x ,..). After that you have to select qty value by map and finally calculate the sum of returned value by reduce.

Try this one:

constSIZES=["_2x","_3x","_4x","l","m","s","xl","xs","xxs"],data=[{color:"red",qty:"45",_1x:"0",_2x:"12",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"0"},{color:"red",qty:"45",_1x:"0",_2x:"9",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"0"},{color:"red",qty:"45",_1x:"0",_2x:"0",_3x:"12",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"0"},{color:"red",qty:"45",_1x:"0",_2x:"0",_3x:"12",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"0"},{color:"red",qty:"65",_1x:"0",_2x:"0",_3x:"0",_4x:"12",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"0"},{color:"red",qty:"65",_1x:"0",_2x:"0",_3x:"0",_4x:"12",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"0"},{color:"pink",qty:"65",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"14",xl:"0"},{color:"red",qty:"68",qty:"0",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"14",xl:"0"},{color:"red",qty:"0",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"14",l:"0",xl:"0"},{color:"red",qty:"0",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"12",l:"0",xl:"0"},{color:"red",qty:"0",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"14",m:"0",l:"0",xl:"0"},{color:"pink",qty:"13",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"14",m:"0",l:"0",xl:"0"},{color:"yellow",qty:"16",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"12"},{color:"pink",qty:"19",_1x:"0",_2x:"0",_3x:"0",_4x:"0",xxs:"0",xs:"0",s:"0",m:"0",l:"0",xl:"12"}];

        const result1 = Object.values(
            data.reduce((acc, { color, size, ...rest }) => {
                if (!acc.hasOwnProperty(color)) {
                    acc[color] = {
                        color,
                        ...rest
                    };
                    return acc;
                }

                Object.keys(rest).forEach(key => {
                    acc[color][key] = (+acc[color][key] || 0) + +rest[key];
                });

                return acc;
            }, {})
        );


        for (var i = 0; i < result1.length; i++) {
            var items = data.filter(t => t.color == result1[i].color);
            for (var j = 0; j < SIZES.length; j++) {
                result1[i][SIZES[j]] = items.filter(t => t[SIZES[j]] > 0).map(t => t.qty).reduce((a, b) => +a + +b, 0);
            }
        }


        console.log(result1)

Post a Comment for "How To Display The Quantity Based On The Size"