0

In the following example, I used square brackets to recall the values for "hours" and "minutes" in an attempt to add them together. This did not work. Is there a way to add two values together like this?

let movies = [
  {
    title: "Rosaline",
    hours: 1,
    mintues: 36,
    totalLength: [hours] * 60 + [minutes],
  },
  {
    title: "The Good Nurse"
    hours: 2,
    mintues: 3,
    totalLength: [hours] * 60 + [minutes],
  }
 ]
d50org
  • 83
  • 6
  • 1
    Are you sure you need to save that at all? You could calculate it each time you need it instead. The problem with the calculation is that when hours or minutes changes, totalLengh will not update, so you will need to update both each time you make any changes. – nycynik Jan 16 '23 at 01:14
  • @nycynik - Yes, that's exactly why I was looking for a solution. I had been updating the data redundantly. Not a major issue, but why add extra work or allow opportunity for error if there's a better solution. Stephen Quan's answer worked perfectly for me. – d50org Jan 17 '23 at 21:23

3 Answers3

1

No such syntax exists in JavaScript. You can do what you are attempting in 2 ways:

Option 1

Create the objects using a function or a class constructor:

function createMovie(title, hours, minutes) {
    return {
        title,
        hours,
        minutes,
        totalLength: hours * 60 + minutes
    };
}
let movies = [
    createMovie("Rosaline", 1, 36)
];

Option 2

Do a pass over the array to correct the information post construction

const calculateTotalLength = (movie) => movie.totalLength = movie.hours * 60 + movie.minutes;
let movies = [{
    title: "Rosaline",
    hours: 1,
    minutes: 36,
    totalLength: 0 // recalculated below
}];
movies.forEach(calculateTotalLength);
Nikola Dimitroff
  • 6,127
  • 2
  • 25
  • 31
1

Those properties do not yet exist, simply because the object that you think you are referencing does not yet exist. It is still in the process of being created.

You can do it like this instead, with a helper lambda function:

const movie = (title, hours, minutes) => ({title, hours, minutes, totalLength: hours * 60 + minutes});

let movies = [
  movie("Rosaline", 1, 36), 
  movie("The Good Nurse", 2, 3) 
];

console.log(movies);
Peter B
  • 22,460
  • 5
  • 32
  • 69
1

Since totalLength is a computed value, you can return totalLength with a getter. The advantage of this approach, should hours or minutes change, then the next time totalLength is retrieved, it will reflect the change.

let movies = [
  {
    title: "Rosaline",
    hours: 1,
    minutes: 36,
    get totalLength() { return this.hours * 60 + this.minutes; }
  },
  {
    title: "The Good Nurse",
    hours: 2,
    minutes: 3,
    get totalLength() { return this.hours * 60 + this.minutes; }
  },
 ];

console.log(JSON.stringify( movies, undefined, 2 ) );
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75