Aquí hay una lista de matrices.
const list = [ { id: 5844, option: 'fruit' children: ['apple', 'banana', 'pear'] }, { id: 5845, option: 'vegetables' children: ['tomato', 'potato', 'spinach'] } ]Quiero obtener una nueva matriz como esta
manzana de los hijos de la fruta es el índice 0
el tomate de los hijos de las verduras es indice = 0
por lo que son coincidentes
[['apple', 'tomato'], ['banana', 'potato'], ['pear', 'spinach']]Creo que podemos probar este fragmento de código.
const list = [ { id: 5844, option: 'fruit', children: ['apple', 'banana', 'pear'] }, { id: 5845, option: 'vegetables', children: ['tomato', 'potato', 'spinach'] } ] var ans = [] list.forEach(item => { item.children.forEach((child, index) => { if (!ans[index]) { ans[index] = [] ans[index].push(child) } else { ans[index].push(child) } }) })Con esta solución, no importa cuántos objetos haya en la matriz. Puede map sobre los elementos secundarios en el primer objeto y usar su longitud para devolver un flatMap de los elementos secundarios.
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));Supongo que tus hijos tienen la misma longitud. Podemos usar 2 bucles para agrupar el elemento de los niños.
Primer ciclo para iterar el elemento de los niños.
Segundo bucle para iterar el elemento de la lista.
Aquí hay un código simple para resolver su caso.
var listSize = list.length; var childSize = list[0].children.length; var expectedArrs = []; for(var i=0;i<childSize;i++){ var groupByChild = []; for(var j=0;j<listSize;j++){ groupByChild.push(list[j].children[i]); } expectedArrs.push(groupByChild); } console.log(expectedArrs);El resultado de la consola:
[["apple", "tomato"], ["banana", "potato"], ["pear", "spinach"]]