0

The drinks: reference inside the object of the array passengers is not retrieving the ticket: value. How do I refer to the outer objects ticket value from inside the array?

var passengers = [ { name: 'Jane Doloop', paid: true, ticket: 'coach', drinks: [ticketDrinks(this.ticket, 0), ticketDrinks(this.ticket, 1)] },
                   { name: 'Dr.Evel', paid: true, ticket: 'firstclass' },
                   { name: 'Sue Property', paid: false, ticket: 'firstclass' },
                   { name: 'John Funcall', paid: true, ticket: 'coach' } ];




function ticketDrinks(ticket, location1) {
    console.log(ticket, location1);
    if (ticket == 'firstclass') {
        drink1 = 'cola';
        drink2 = 'water';
        if (location1 == 0) {
            return drink1;
        } else {
            return drink2;
        }

    } else if (ticket == 'coach') {
        drink1 = 'wine';
        drink2 = 'champagne';
        if (location1 == 0) {
            return drink1;
        } else {
            return drink2;
        }
    }
    return null;
}
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • 1
    The linked question is for object initializers, but it's the same answer for array initializers (JavaScript arrays are, after all, just a special case of objects). – T.J. Crowder Apr 29 '17 at 15:51

1 Answers1

0

Instead of:

{
    name: 'Jane Doloop',
    paid: true,
    ticket: 'coach',
    drinks: [ticketDrinks(this.ticket, 0), ticketDrinks(this.ticket, 1)]
}

You can do:

{
    name: 'Jane Doloop',
    paid: true,
    ticket: 'coach',
    drinks: [0, 1]
}

Then make Array.prototype.map() to iterate over the array of objects and dynamically access to the property tikets.

And than, you make another Array.prototype.map() to call the method ticketDrinks() passing the current object property drinks.

Code:

var passengers = [{name: 'Jane Doloop',paid: true,ticket: 'coach',drinks: [0, 1]},{name: 'Dr.Evel',paid: true,ticket: 'firstclass'},{name: 'Sue Property',paid: false,ticket: 'firstclass'},{name: 'John Funcall',paid: true,ticket: 'coach'}],
    ticketDrinks = function (ticket, location1) {
      console.log(ticket, location1);
      var drink1, drink2;
      if (ticket === 'firstclass') {
        drink1 = 'cola';
        drink2 = 'water';
        return location1 === 0 ? drink1 : drink2;
      } else if (ticket === 'coach') {
        drink1 = 'wine';
        drink2 = 'champagne';
        return location1 === 0 ? drink1 : drink2;
      }
      return null;
    },
    result = passengers.map(function (user) {
      if (user.drinks) {
        user.drinks = user.drinks.map(function (location) {
          return ticketDrinks(user.ticket, location)
        });
      }

      return user;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46