0

Please feel free to modify title, it was rather hard for me to explain and thus search.

var booking = [
 {
    x: "1",
    y: "2",
    days: [
       {
           hours: 8
       },     
    ]
 },
 {...}
]

var hoursBooked = [8, 2, 4, 8, 2, 8, 3, 4]; // this is what I want

So I have an array of 'Booking' objects. Each Booking can have a number of days in an array of 'Day' objects. In the 'Day' object lies an 'Hours' property.

All I want to do - is loop through the bookings array and output a flattened array of 'Hours' values (so I can visualise in a graph).

I am sure there's a nice functional or otherwise clean approach to doing this rather than using a sequence of 'for' loops.

Anyone?

aspirant_sensei
  • 1,568
  • 1
  • 16
  • 36
  • at least, you could add a classical approach to the question. – Nina Scholz May 24 '17 at 10:51
  • Do you mean in terms of what I have already attempted? The solution I had used was nested for loops, but I specified in the question I wasn't looking for that answer and instead something more functional – aspirant_sensei May 24 '17 at 10:58

3 Answers3

2

Lodash 4x

var booking = [
 {
    x: "1",
    y: "2",
    days: [
       {
           hours: 8
       },     
    ]
 },
 {
    x: "1",
    y: "2",
    days: [
       {
           hours: 3
       },  
       {
           hours: 5
       }   
    ]
 }
];


_(booking).map('days').flatten().map('hours').value();

Will print

[8, 3, 5]
ninhjs.dev
  • 7,203
  • 1
  • 49
  • 35
1

You could reduce booking with the values of the days arrays.

var booking = [{ x: "1", y: "2", days: [{ hours: 8 }, { hours: 4 }, ] }, { x: "3", y: "4", days: [{ hours: 1 }, { hours: 3 }, ] }, { x: "3", y: "4", days: [] }],
    hoursBooked = booking.reduce((r, a) => r.concat((a.days || []).map(d => d.hours)), []);

console.log(hoursBooked);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

var booking = [
 {
    x: "1",
    y: "2",
    days: [
       {
           hours: 8
       },     
       {
           hours: 2
       }
    ]
 },
 {
    x: "1",
    y: "2",
    days: [
       {
           hours: 4
       },     
    ]
 }
]
var hoursBooked = []
booking.forEach(b=>b.days.forEach(d=>hoursBooked.push(d.hours)))
console.log(hoursBooked)
Michał Sałaciński
  • 2,256
  • 1
  • 11
  • 10