I have a var K with several parameters A, B, L, M. I'm trying to put an increment/decrement box to "A" so it can be changed to a larger or smaller number.
If this is possible, it should remain changed (saved?) for the next time or session it is loaded.
{ L: 34, M: 56, A: 64, B: 65 },
{ L: 35, M: 55, A: 47, B: 89 },
{ L: 36, M: 54, A: 85, B: 62 },
{ L: 37, M: 53, A: 23, B: 11 }, ];
CodePudding user response:
Since the question is tagged with reactjs, I assume this array of objects being in a component state, so we have to do it without mutating the original array.
Safest way to do it is by using a map() method from Array.prototype.
Example:
const K = [{ L: 34, M: 56, A: 64, B: 65 }, { L: 35, M: 55, A: 47, B: 89 }];
const newArray = K.map(element => ({...element, A: element.A 1}));
console.log(newArray);
//[{ L: 34, M: 56, A: 65, B: 65 }, { L: 35, M: 55, A: 48, B: 89 }]
And now explanation. Map is a method that takes a function as an argument, where first parameter is actual value in each index of an array and returns a new value in it's place.
What's done here in ({...element, A: element.A 1})
, is that the object got populated with the properties from "element", then property A got overwritten with value of element.A 1. After that it got returned as a new value. It happened the same for every single key.
The end result is a new array with each A increased by 1 and assigned to newArray.
And if it has to stay in a session, just keep it in a sessionStorage.
Useful links:
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map