Context: I'm creating an object to set the color "red" to the latest slice in google charts, however, I keep getting "stacked" objects. I'd like to remove the previous objects and keep only the latest object available.
I was trying to do something like this:
let indices = indexSum;
for (let i = 1; i <= slices.length; i++) {
if (Object.keys(lossColor).length >= 2) {
delete lossColor[i - 1];
}
lossColor[i] = { color: "red" };
}
Basically, as soon as the number of objects in my initial object is 2, I'd like to remove the previous index (hence the i-1).
I was also trying to use the spread operator (thanks to a user in SO that replied to one of my other questions) to replace the existing objects with the latest object added.
This was his implementation (however, I keep getting all the objects added without removing the previous ones)
for (let i = 1; i <= indices; i++) {
lossColor = { ...lossColor, [i]: { color: "red" } };
}
I'm currently getting something like this if the user adds 3 inputs:
{
"1": {
"color": "red"
},
"2": {
"color": "red"
},
"3": {
"color": "red"
}
}
The goal is to have something like this:
{
"3": {
"color": "red"
}
}
Where basically all other objects are removed and only the latest one is kept
Is there a better way to do this? Thank you in advance
If it is always the last you can simply omit the spread operator out of the equation like this,
var lossColor = [];
for (let i = 1; i <= 3; i++) {
lossColor = {[i]: { color: "red" } };
}
console.log(lossColor);
A great article about spread operator if you are not sure where using it : https://learnjsx.com/category/2/posts/es6-spreadOperator