Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda