Tengo una matriz formateada así
const array = [ ['technology', 'apple', 'computers', 'macbook_pro'], ['technology', 'apple', 'computers', 'macbook_air'], ['technology', 'apple', 'phones', 'iphone'], ['technology', 'samsung', 'phones', 'Galaxy S21'], ]Y necesito convertirlo en un objeto formateado así:
{ technology: { apple: { computers: { macbook_pro: {}, macbook_air: {} }, phones: { iphone: {} } }, samsung: { phones: { galaxy_s21: {} } } } }Intenté hacerlo con dos bucles forEach pero sigo atascado.
Usando Array#reduce , itere sobre la matriz mientras actualiza un acumulador de objetos.
En cada iteración, establezca una current en el acumulador e itere sobre la lista actual usando Array#forEach . Si current no tiene una propiedad, establezca el valor en {} usando el nullish operator . Luego, restablezca current para usarla en la próxima iteración.
const array = [ ['technology', 'apple', 'computers', 'macbook_pro'], ['technology', 'apple', 'computers', 'macbook_air'], ['technology', 'apple', 'phones', 'iphone'], ['technology', 'samsung', 'phones', 'Galaxy S21'], ]; const res = array.reduce((acc, props) => { let current = acc; props.forEach(prop => { current[prop] ??= {}; current = current[prop]; }); return acc; }, {}); console.log(res);La implementación Array.reduce se agrega a continuación
array de entrada const array = [ ['technology', 'apple', 'computers', 'macbook_pro'], ['technology', 'apple', 'computers', 'macbook_air'], ['technology', 'apple', 'phones', 'iphone'], ['technology', 'samsung', 'phones', 'Galaxy S21'], ] const output = array.reduce((acc, curr) => { let temp = acc; curr.forEach((node) => { if (!temp[node]) { temp[node] = {} } temp = temp[node] }) return acc; }, {}); console.log(output)