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

116
Visualizações
JavaScript merge array objects with the same keys

I have an array with several objects some have the same keys (Question and QuestionId), for example:

    var jsonData = [
            {
                Question: "Was the training useful?",
                QuestionId: 1,
                myData: [{ name: 'No', value: 1 }] },
            {
                Question: "Was the training useful?",
                QuestionId: 1 ,
                myData: [{ name: 'Yes', value: 1 }]
        }];

How can I combine these objects into one, expected output:

      var jsonData = [
        {
            Question: "Was the training useful?",
            QuestionId: 1,
            myData: [{ name: 'No', value: 1 },
                     { name: 'Yes', value: 1 }] 
          }];
about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

var jsonData = [{
    Question: "Was the training useful?",
    QuestionId: 1,
    myData: [{
      name: 'No',
      value: 1
    }]
  },
  {
    Question: "Was the training useful?",
    QuestionId: 1,
    myData: [{
      name: 'Yes',
      value: 1
    }]
  }
];

const result = Object.values(jsonData.reduce((acc, obj) => {
  if (!acc[obj.QuestionId]) {
    acc[obj.QuestionId] = obj;
  } else {
    acc[obj.QuestionId].myData = acc[obj.QuestionId].myData ?? []; // if myData is null or undefined, set it to an empty array
    acc[obj.QuestionId].myData = acc[obj.QuestionId].myData.concat(obj.myData);
  }
  return acc;
}, {}));

console.log(result);

about 4 years ago · Santiago Gelvez Relatório

0

function mergeData(data) {
  const acc = {}
  data.forEach(x => {
    const id = x.QuestionId
    if (!acc[id]) acc[id] = x
    else acc[id].myData = acc[id].myData.concat(x.myData)
  })
  return Object.values(acc)
}
about 4 years ago · Santiago Gelvez Relatório

0

You can use forEach to create an object where the keys are the question IDs and then use Object.values to get the values into an array.

var jsonData = [{
  Question: "Was the training useful?",
  QuestionId: 1,
  myData: [{ name: 'No', value: 1 }] 
}, {
  Question: "Was the training useful?",
  QuestionId: 1 ,
  myData: [{ name: 'Yes', value: 1 }]
}];

var temp = {};
jsonData.forEach(x=>{
  if(!temp[x.QuestionId]) {temp[x.QuestionId] = x;} 
  else {temp[x.QuestionId].myData.push(x.myData);}
});

var arr = Object.values(temp);

console.log(arr);

about 4 years ago · Santiago Gelvez 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