Home > Software design >  How can i update an array of objects on each iteration to add a new given object on that array if th
How can i update an array of objects on each iteration to add a new given object on that array if th

Time:10-26

I'm trying to make a function that does the job of a POS billing section. when an item is clicked to grab and pass the values of an item (name, price, qty ...) to into an object and then the object is passed into the function as an argument. each item should exist only once and if the same item is clicked more than once it should only update the value of the "qty" propertiy by 1 and keep the track. i'm storing all he objects in an array called totalItems. i'm stuck at the qty value updating part it's crashing and getting different kind of issues. please help .

// THIS ARE THE OBJECT PROPERTIES 
// {
//     img: '',
//     name: '',
//     price: 0,
//     qty: 1
// }

let totalItems = []

const sumTotalItems = (obj) => {
    if (totalItems.length) {
        totalItems.map((item) => {
           if (obj.name === item.name) {
            const index = totalItems.indexOf(item)
            const newItem = item = {...item, qty: item.qty  = 1}
            const updatedArray = totalItems.splice(index, 1, newItem)
            return totalItems = [...updatedArray]
           } else {
            return totalItems = [...totalItems, obj]
           }
        })
    } else {
        return totalItems = [obj]     
    }
    console.log(totalItems)
}

CodePudding user response:

let totalItems = []

const sumTotalItems = (obj) => {
    const currentIndex = totalItems.findIndex((item) => item.name === obj.name)
    if (currentIndex >= 0) {
        totalItems[currentIndex].qty  = 1
    } else {
        totalItems.push({...obj, qty: 1})
    }
    console.log(totalItems)
}

sumTotalItems({name: 'a'})
sumTotalItems({name: 'b'})
sumTotalItems({name: 'a'})
sumTotalItems({name: 'c'})
sumTotalItems({name: 'b'})
sumTotalItems({name: 'c'})

CodePudding user response:

you can do something like this

let totalItems = []

const addItem = ( item) => {
  const items = totalItems.reduce((res, i) => {
    return {
     ...res,
     [i.name]: i
    }  
    }, {}) 
   
   const existing = items[item.name] || {...item, qty: 0}
   existing.qty  = item.qty
   
   items[item.name] = existing
   
   return Object.values(items)
}
const item1 = {
  img: 'img1',
  name: 'item1',
  price: 1,
  qty: 1
}

const item2 = {
  img: 'img2',
  name: 'item2',
  price: 2,
  qty: 2
}

totalItems = addItem(item1)
console.log(totalItems)


totalItems = addItem(item1)
console.log(totalItems)

totalItems = addItem(item1)
console.log(totalItems)


totalItems = addItem(item2)
console.log(totalItems)

  • Related