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

175
Views
JavaScript modifica la matriz de objetos y altera los datos contenidos

Tengo dificultades para formatear algunos datos. Actualmente, recibo datos en la siguiente estructura.

 [ { "q1":"5", "q2":[ "13", "12", ], "q3":"test", } ]

Básicamente, necesito modificar esto o incluso crear un nuevo objeto, que tenga la siguiente estructura.

 [ { id: 1, //q1 answers: [ { answer: '5', }, ], }, { id: 2, //q2 answers: [ { answer: '13', }, { answer: '12', }, ], }, { id: 3, //q3 answers: [ { answer: 'test', }, ], }, ];

Entonces, la identificación en lo anterior se obtendría eliminando la q y obteniendo el número en el primer objeto de datos. Entonces tendría una matriz de respuestas que tendría un objeto para cada respuesta.

He estado intentando esto pero me he perdido. No sé si debo usar bucles, mapas, filtros, etc. Para ser honesto, lo más lejos que he llegado hasta ahora es obtener las claves.

 var modified = data.map(function(item) { return Object.keys(item) })

Creé un JSFiddle donde he estado intentando hacer esto.

¿Hay alguna manera de que pueda obtener los datos que busco?

Muchas gracias

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

0

Utilice la función de mapa.

 const data = { "q1":"5", "q2":[ "13", "12", ], "q3":"test", }; const result = Object.keys(data).map(key => { let item = {id: key.substring(1), answers: []}; if(typeof data[key] === "string") item.answers.push({answer: data[key]}); else item.answers = data[key].map(val => ({answer: val})); return item; }); console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

 const inputData = [ { "q1":"5", "q2":[ "13", "12", ], "q3":"test", } ] function answerMapper(objVal, id){ return Array.isArray(objVal) ? { id, answers: objVal.map(answer => ({ answer }))} : { id, answers: [{answer: objVal }] } } function formatObject(obj){ return Object.keys(obj).map((k, i) => answerMapper(obj[k], i+1)); } const result = inputData.map(obj => formatObject(obj)); // remove flatMap if your inputData has more than one entry console.log(result.flatMap(x => x));

about 4 years ago · Juan Pablo Isaza Report

0

vamos a crear una función pura que acepta el objeto en la matriz como tal

 const processObject = obj => Object.keys(obj).map(id => { const answer = obj[id]; const answers = Array.isArray(answer) ? answer : [answer] const answerObjectArray = answers.map(ans => ({ answer: ans })); return { id: +id.substring(1), answers: answerObjectArray } }); const dataArray = [{ "q1": "5", "q2": [ "13", "12", ], "q3": "test", }]; const output = processObject(dataArray[0]); console.log(output);

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!