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

174
Vistas
JavaScript modify Array of Objects and alter contained data

I am having difficulties formatting some data. Currently, I receive data in the following structure.

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

I essentially need to modify this or even create a new object, that takes the following structure.

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

So the id in the above would be obtained by remove the q and getting the number in the first data object. It would then have an answers array that would have an object for each answer.

I have been attempting this but have gotten lost. I don't know if I should use loops, mapping, filters etc. To be honest, the furthest I have got so far is obtaining the keys

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

I have created a JSFiddle where I have been attempting to do this.

Is there any way I can achieve the data I am after?

Many thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Please use map function.

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 Denunciar

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 Denunciar

0

lets create a pure function which accepts the object in the array like so

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