从存在于 top-level object 中的 object 数组中检索值的扁平数组,我得到了一个数组

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

请随意修改标题,我很难解释和搜索。

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

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

所以我有一个 'Booking' object 数组。 每个预订可以在 'Day' object 的数组中包含天数。 在 'Day' object 中有一个 'Hours' 属性.

我想做的就是遍历预订数组并输出一个扁平的 'Hours' 值数组(这样我就可以在图表中可视化)。

我确信有一个很好的功能性或其他干净的方法来执行此操作,而不是使用一系列 'for' 循环。

有人吗?

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)

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

将打印

[8, 3, 5]

您可以使用 days 数组的值来减少 booking

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