skip to Main Content

I have the following object in a JS script I’m working on:

let time = {
    years: 0,
    months: 0
};

I also have a global helper function, on a seperate file, that calculates the total years and months given a number of months:

helpers.monthsToYears = function(months) {
    var totalYears = months / 12;
    return [Math.floor(totalYears), Math.round((totalYears - Math.floor(totalYears)) * 12)];
};

I want to update my time array using the global function, but I am unsure as to how to do this simply.

I’ve searched and found ways to create a new object from a function’s output, but not how to update an existing object.

I have tried things like:

    time[years,months] = helpers.monthsToYears(results.months);

but to no result.

Would anyone know the correct way to do this?

2

Answers


  1. You could do

    // destructuring assignment
    const [ years, months ] = helpers.monthsToYears(results.months)
    // that's equivalent to
    // const res = helpers.monthsToYears(results.months)
    // const years = res[0]; const months = res[1]
    
    time = { months, years }
    // or
    // time.months = months
    // time.years = years
    
    Login or Signup to reply.
  2. Depending on the meaning of "update an existing object" you are referring to, based on Zac Anger’s answer above, you can also perform:

    time.years += years;
    time.months += months;
    
    if (time.months >= 12) {
        time.years += Math.floor(time.months / 12);
        time.months = time.months % 12;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search