Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
Cómo convertir una matriz de matrices en un objeto en Javascript

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...

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

recursividad simple:

  1. Caso base: solo tenemos una matriz dentro de la matriz. Construimos un objeto con valores predeterminados a partir de él.
  2. Paso recursivo: tenemos más matrices. Construimos un objeto y cada clave proviene de la primera matriz, cada valor es una llamada recursiva que usa el resto de las matrices:

 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 default

También puede ser representado por:

  1. Caso base: devuelve el valor predeterminado.
  2. Paso recursivo: construimos un objeto y cada clave proviene de la primera matriz, cada valor es una llamada recursiva que usa el resto de las matrices.

 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 default

about 4 years ago · Juan Pablo Isaza Report

0

Creo 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)
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!