Skip to content Skip to sidebar Skip to footer

Update Property Of Every Object In Array In React Js Function

I have an array of objects. I want to update one property of every object in the array inside a function. I declare a function outside render: const computePiePercentages = funct

Solution 1:

The map() method creates a new array with the results of calling a provided function on every element in the calling array. So you must return a value from callback function for the new array, as it doesn't modify existing array.

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

So below should fix the issue for you :

const computePiePercentages = function(pieChartData, remainingBudget){
  var denominator = 1600;
  if(remainingBudget > 0){
    denominator = 1600 - remainingBudget
  }


  return pieChartData.map((val, j) => {
    let newVal = Object.assign({}, val);
    newVal.y = Number((newVal.y / denominator).toFixed(1)) * 100return newVal;
  });


  };

Solution 2:

The problem is that you don't have a return value in your map function:

return pieChartData.map(val => {
  val.y = Number((val.y / denominator).toFixed(1)) * 100returnval;
});

Also, consider just storing this modified version of pieChartData, so the value doesn't need to be computed each time the component is rendered.

Post a Comment for "Update Property Of Every Object In Array In React Js Function"