Necesito la solución para el caso general.
por ejemplo
let data = [['a', 'b'],['c', 'd'],['e', 'f', 'g', 'h']];Necesito este:
{ "a": { "c": { "e": 0, "f": 0, "g": 0, "h": 0 }, "d": { "e": 0, "f": 0, "g": 0, "h": 0 } }, "b": { "c": { "e": 0, "f": 0, "g": 0, "h": 0 }, "d": { "e": 0, "f": 0, "g": 0, "h": 0 } } }y los datos pueden ser cualquier matriz aleatoria de matrices... Intenté un enfoque recursivo pero me quedé atascado con el método Map y .fromEntries...
recursividad simple:
const buildObj = (data, defaultValue = 0) => { if (data.length > 1) return Object.fromEntries( data[0].map(x => [x, buildObj(data.slice(1), defaultValue)]) ) return Object.fromEntries( data[0].map(x => [x, defaultValue]) ); } console.log(buildObj([ ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['c', 'd'], ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ], 42)); //different defaultTambién puede ser representado por:
const buildObj = (data, defaultValue = 0) => { if (data.length !== 0) return Object.fromEntries( data[0].map(x => [x, buildObj(data.slice(1), defaultValue)]) ); return defaultValue; } console.log(buildObj([ ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['c', 'd'], ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ], 42)); //different defaultCreo que esto funciona bien. Ejecuta recursividad con paso. Puede cambiar forEach a for loop, si lo desea.
let data = [['a', 'b'],['c', 'd'],['e', 'f', 'g', 'h']]; const arrToDict = (data) => { const recursive = (depth = 0) => { let dict = {} if (data.length === depth + 1) { data[depth].forEach(el => { dict[el] = 0 }) } else { data[depth].forEach(el => { dict[el] = recursive(depth+1) }) } return dict } return recursive(); } arrToDict(data)He usado una recursividad para convertir cada índice en objeto y luego usé Memoización para una solución más eficiente
Caso base : cuando el índice ha salido de los límites de la matriz actual Caso recursivo : recurse al siguiente índice y asigne el siguiente índice objetivado como un valor a la clave actual
//store the index which is already iterated/objectified //this is just for LESS COMPUTATION and MORE EFFICIENCY const memoizeObjectifiedIndex = {}; let data = [['a', 'b'],['c', 'd'],['e', 'f', 'g', 'h']]; //basic recursive approach function createObject(data,index){ //base case, //if the index is just outside the length of array, //here that index=3, since array is 0 indexed and last index is 2 if(index === data.length) return 0; //check in memoized object if current index is already objectfied if(memoizeObjectifiedIndex[index]){ //you can check the hits when this condition is true and COMPUTATION is saved // console.log("Found for index ", index); return memoizeObjectifiedIndex[index];} const obj={}; data[index].forEach((key) => { //assign the next objectified index as value to current key obj[key] = createObject(data,index+1); }) //store the object for current index for future use memoizeObjectifiedIndex[index] = obj; return obj; } console.log(createObject(data,0))Nota : puede ver un mejor resultado copiando y ejecutando este código en la consola del navegador.