如何提取数组中的数组并将其构造为一个完整的数组?

How do I extract the array in an array and structure it to be one whole array?

如何提取数组中的数组并将其构建为一个完整的数组?

输入:

const input = [{
    categoryName: "Chinese food",
    tabs: [{
        header: "Chicken Rice",
        content: "Hainanese chicken rice is a dish of poached chicken and seasoned rice"
      },
      {
        header: "Dim sum",
        content: "large range of small Chinese dishes that are traditionally enjoyed in restaurants"
      }
    ]
  },
  {
    categoryName: "Italian food",
    tabs: [{
      header: "Pizza",
      content: "Dish of Italian origin consisting of a usually round"
    }]
  },
]

输出(需要把所有的header都提取出来成为这个数组)

const output = [
  {
    "categoryName": "Chinese food",
    "header": "Chicken Rice",
  },
  {
    "categoryName": "Chinese food",
    "header": "Dim sum",
  },
  {
    "categoryName": "Italian food",
    "header": "Pizza"
  },
]

下面的解决方案实现了下面假定的 target/objective:

The header always be nested in the same, uniform way. i.e, it will always be in the tabs prop array & the tabs prop will always be present in each object in the input array.

代码段

// extract only 'header', and included 'id'
const getHeadersWithId = arr => (
  arr.flatMap(                    // iterate over 'input' array and 'flat'-ten the result
    ({tabs}) => (tabs.map(        // de-structure 'tabs' & iterate over it
      ({header}) => ({header})    // de-structure 'header' & retain it to intermediate-result array
    ))
  ).map(
    ({header}, idx) => ({         // iterate with index 'idx'
      id: idx+1,                  // generate the 'id' and store
      header                      // header from intermediate-result array element
    })
  )
);

const input = [{
    categoryName: "Chinese food",
    tabs: [{
        header: "Chicken Rice",
        content: "Hainanese chicken rice is a dish of poached chicken and seasoned rice"
      },
      {
        header: "Dim sum",
        content: "large range of small Chinese dishes that are traditionally enjoyed in restaurants"
      }
    ]
  },
  {
    categoryName: "Italian food",
    tabs: [{
      header: "Pizza",
      content: "Dish of Italian origin consisting of a usually round"
    }]
  },
];

console.log(getHeadersWithId(input));

说明

在上面的代码段中添加了内联评论。