Search code examples
javascriptobjectiterationunderscore.jsdata-munging

Retrieve a flattened array of values taken from an object array that exists within a top-level object of which I am given an array


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?


Solution

  • 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);