How do I convert an array object into a two-dimensional array

Here is a Array list.

const list = [
  {
    id: 5844,
    option: 'fruit'
    children: ['apple', 'banana', 'pear']
  },
  {
   id: 5845,
   option: 'vegetables'
   children: ['tomato', 'potato', 'spinach']
  }
]


I want to get a new array like this

apple of fruit’s children is index 0

tomato of vegetables’s children is index = 0

so they are match

[['apple', 'tomato'], ['banana', 'potato'], ['pear', 'spinach']]

Answer

With this solution it doesn’t matter how many objects are in the array. You can map over the children in the first object and use it’s length to return a flatMap of the children elements.

const list=[{id:5844,option:"fruit",children:["apple","banana","pear"]},{id:5845,option:"vegetables",children:["tomato","potato","spinach"]},{id:5846,option:"buildings",children:["church","warehouse","skyscraper"]}];

function getNewData(list) {

  // `map` over the children in the first object
  // using its index to return a new flattened array
  // of all array object children
  return list[0].children.map((_, i) => {
    return list.flatMap(obj => obj.children[i]);
  });
}

console.log(getNewData(list));