Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
Conversión de una matriz de datos a JSON mediante un mapa de propiedades

Estoy tratando de convertir una matriz 2d en un objeto json usando un mapa clave. El mapa clave parece

 var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.mobile' ];

y los datos son

 var data = [ [1, 'Task 1', 'C1', 'Customer 1', '999', '8888'], [2, 'Task 2', 'C2', 'Customer 2', '333', '5555'] ];

La salida JSON debe ser

 var output = [ { "id":1, "title":"Task 1", "customer":{ "id":"C1", "name":"Customer 1", "phone":{ "home":"999", "mobile":"8888" } } }, { "id":2, "title":"Task 2", "customer":{ "id":"C2", "name":"Customer 2", "phone":{ "home":"333", "mobile":"5555" } } } ];

Estoy tratando de hacerlo pero no soy bueno aquí haciendo smerecursion, etc. ¿Alguien podría ayudarme, por favor?

 function arrToJSON(headers, data){ var output = []; data.forEach(row, index){ var cObj = {}; headers.forEach(header, itemIndex){ var headerParts = header.split('.'); // NOt sure what to do here } } }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Puede lograr fácilmente el resultado usando map y reduce en js.

 createObj(acc, curr.split("."), 0, o[index]);

es la función que se usa en recursividad y eso es lo que estás buscando.

Arguments

 createObj( acc, // object in which you want to add value curr.split("."), // send path as an array 0, // current index in path, initially zero o[index] // value to be assigned ); 

 var keys = [ "id", "title", "customer.id", "customer.name", "customer.phone.home", "customer.phone.mobile", ]; var data = [ [1, "Task 1", "C1", "Customer 1", "999", "8888"], [2, "Task 2", "C2", "Customer 2", "333", "5555"], ]; function createObj(obj, arr, index, value) { if (index === arr.length - 1) obj[arr[index]] = value; else { if (!obj[arr[index]]) obj[arr[index]] = {}; createObj(obj[arr[index]], arr, index + 1, value); } } const result = data.map((o) => { return keys.reduce((acc, curr, index) => { createObj(acc, curr.split("."), 0, o[index]); return acc; }, {}); }); console.log(result);
 /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede usar simplemente desestructurar y extender el operador con reducir.

 var data = [ [1, "Task 1", "C1", "Customer 1", "999", "8888"], [2, "Task 2", "C2", "Customer 2", "333", "5555"], ]; const buildObject = (arr = []) => { return arr.reduce((acc, [id, title, cid, name, home, mobile]) => { const row = { id, title, customer: { id: cid, name, phone: { home, mobile } }, }; return acc.concat(row); }, []); }; console.log(buildObject(data));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda