简体   繁体   中英

sum values, and merge object values ​with the same id into a new array

I have an item object that I receive from the server. Each item and its quantity has to be saved with the seller, however, at the time of showing on the screen, I need the values ​​to be totaled independent of the seller in a new array.

[
    { code: 1, item: 'ball', salesman: 'Braan', quantity: 5, price: 10.00},
    { code: 1, item: 'shoe', salesman: 'Alex', quantity: 5, price: 20.00},
    { code: 1, item: 'ball', salesman: 'Max', quantity: 3, price: 10.00},
    { code: 1, item: 'shirt', salesman: 'Braan', quantity: 5, price: 15.00}
]

the desired output would be:

[
    { code: 1, item: 'ball', quantity: 8, price: 20.00},
    { code: 1, item: 'shoe', quantity: 5, price: 20.00},
    { code: 1, item: 'shirt', quantity: 5, price: 15.00}
]

basically you can remap your object to remove the salesman key.

 const serverData = [{ code: 1, item: 'ball', salesman: 'Braan', quantity: 5, price: 10.00 }, { code: 1, item: 'shoe', salesman: 'Alex', quantity: 5, price: 20.00 }, { code: 1, item: 'ball', salesman: 'Max', quantity: 3, price: 10.00 }, { code: 1, item: 'shirt', salesman: 'Braan', quantity: 5, price: 15.00 } ] const result = serverData .map((item, i, array) => { const defaultValue = { code: item.code, item: item.item, quantity: 0, price: 0 } const finalValue = array .filter(other => other.item === item.item) //we filter the same items .reduce((accum, currentVal) => { //we reduce them into a single entry accum.quantity += currentVal.quantity; accum.price += currentVal.price; return accum; }, defaultValue); return finalValue; }) .filter((item, thisIndex, array) => { //now our new array has duplicates, lets remove them const index = array.findIndex((otherItem, otherIndex) => otherItem.item === item.item && otherIndex !== thisIndex && otherIndex > thisIndex); return index === -1 }) console.log(result)

Simple use map function to create new array with object with reduced properties.

 const arr = [ { code: 1, item: 'ball', salesman: 'Braan', quantity: 5, price: 10.00}, { code: 1, item: 'shoe', salesman: 'Alex', quantity: 5, price: 20.00}, { code: 1, item: 'ball', salesman: 'Max', quantity: 3, price: 10.00}, { code: 1, item: 'shirt', salesman: 'Braan', quantity: 5, price: 15.00} ]; const newArr = arr.map((obj) => { return { code: obj.code, quantity: obj.quantity, price: obj.price, item: obj.item } }) console.log(newArr)

Try this

 og = [ { code: 1, item: 'ball', salesman: 'Braan', quantity: 5, price: 10.00}, { code: 1, item: 'shoe', salesman: 'Alex', quantity: 5, price: 20.00}, { code: 1, item: 'ball', salesman: 'Max', quantity: 3, price: 10.00}, { code: 1, item: 'shirt', salesman: 'Braan', quantity: 5, price: 15.00} ] var filtered = {}; og.forEach(d => { x = filtered[d.item] || {}; x = { code: d.code, item: d.item, quantity: (x.quantity || 0) + d.quantity, price: (x.price || 0) + d.price } filtered[d.item] = x; }) var fin = Object.keys(filtered).map(item => filtered[item]) console.log(fin)

Although I would suggest creating a map of all the item types, as that would be easily accessible.

You could reduce the array by grouping by item and assuming the same price.

 var data = [{ code: 1, item: 'ball', salesman: 'Braan', quantity: 5, price: 10.00 }, { code: 1, item: 'shoe', salesman: 'Alex', quantity: 5, price: 20.00 }, { code: 1, item: 'ball', salesman: 'Max', quantity: 3, price: 10.00 }, { code: 1, item: 'shirt', salesman: 'Braan', quantity: 5, price: 15.00 }], result = data.reduce((r, { code, item, quantity, price }) => { var temp = r.find(o => o.item === item); if (!temp) { r.push({ code, item, quantity, price }); } else { temp.quantity += quantity; } return r; }, []); console.log(result)

var result = [];
myArray.reduce(function(res, value) {
 if (!res[value.item]) {
res[value.item] = { price: 0,quantity: 0 };
result.push(res[value.item])
}
res[value.item].quantity += value.quantity;
res[value.item].price += value.price;

 return res;
 }, {});

console.log(result)

Thanks everyone, I solved it this way:

mergeEqualsItems(items: any[]) {
        const itemsCopy = JSON.parse(JSON.stringify(items));
        const map = new Map();
        const newArr = [];
        itemsCopy.forEach(elem => {
          if (map.get(elem.id)) {
            const elemMap = map.get(elem.id);
            elemMap.quantity = elemMap.quantity + elem.quantity;
            map.set(elem.id, elemMap);
          } else {
            delete elem.salesman;
            map.set(elem.id, elem);
          }
        });
        map.forEach(elem => newArr.push(elem));
        return newArr;
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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