Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Deleting the previous objects to keep just the latest object available

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!