Home > Blockchain >  how to update all keys with the same name in a array of objects?
how to update all keys with the same name in a array of objects?

Time:10-04

I am using react and redux and would like to decrement each 'volume' key value by a random number between 0 and 20 (both included) then update the state array.

my array is such:

const arr = [
  {id: 1, volume: 100, isEmpty: false},
  {id: 2, volume: 100, isEmpty: false}
]

this is my action:

const decrementAction = () => {
    return {
        type : 'DECREMENT'
    }
}

my reducer is such:

const containers = (state = arr, action) => {
  switch(action.type){
    case 'DECREMENT':
      const randomNumber = Math.floor(Math.random() * 20)   0;
      const newArr = arr.map(item => {
        const newObj = {
          ...item,
          volume : item.volume - randomNumber
        }
        return newObj;
      });
      state = newArray
  }
};

I am having a couple of issues when running my code:

1 - each value is the same as opposed to getting a random value for each object (solved)

2 - the values are both incremented and decremented as opposed to only being decremented

please, what am I doing wrong?

thanks

CodePudding user response:

Firstly you are getting the random number only once. You need a new random number every time.

Try to run the whole thing in a loop and keep adding items by destructuring them as you are doing currently.

const containers = (state = arr, action) => {
  switch(action.type){
    case 'DECREMENT':
      let newArr = [];
      for(let i = 0 ; i < arr.length; i  ) {
      const randomNumber = Math.floor(Math.random() * 20)   0;
       const newObj = {
          ...arr[i],
          volume : item.volume - randomNumber
        };
      newArr.push(newObj);
      }
      return newArr;
      break;
   
   }
};

Also I believe with redux you are supposed to return the state.

CodePudding user response:

Consider putting a break; after state = newArray in your reducer, that should at least resolve your second issue:

 const containers = (state = arr, action) => {
  switch(action.type){
    case 'DECREMENT':
      const randomNumber = Math.floor(Math.random() * 20)   0;
      const newArr = arr.map(item => {
        const newObj = {
          ...item,
          volume : item.volume - randomNumber
        }
        return newObj;
      });
      state = newArray;
      break;
  }
};

Javascript switch reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

  • Related