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

134
Visualizações
How to Merge Objects with same keys?

I have JSON response coming from Node.JS API where Label values are same but other values like dd1, dd2 are different I am trying to merge same label values in one object, How could I achieve this?

   {
      "label": "Medium", 
      "dd1": "Cat A", 
      "dd2": "Non Cision",
       
  },
  {
      "label": "Medium",
      "dd1": "Cat B",
      "dd2": null,
      
  },
  {
      "label": "Tone", 
      "dd1": "Neutral", 
      "dd2": null,
      
  }

Above JSON Objects we can see Label are same in first two so, it should be merge and null values eleminated. like this

  {
      "label": "Medium", 
      "dd1": "Cat A", "Cat B" 
      "dd2": "Non Cision",
       
  }, 
  {
      "label": "Tone", 
      "dd1": "Neutral", 
      "dd2": null,
      
  }

TS Code -

var output = [];
  value.forEach(function(item) {
    var existing = output.filter(function(v, i) {
      return v.label == item.label;
    });
    if (!existing.length) {
      if (typeof item.label == "string") output.push(item);
    }
  });

  console.log(output);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I don't know much about Typescript - this is just a Javascript answer but I'm hoping it might be helpful.

const data = [
  { "label": "Medium", "dd1": "Cat A", "dd2": "Non Cision" },
  { "label": "Medium", "dd1": "Cat B", "dd2": null },
  { "label": "Medium", "dd1": "Cat C", "dd2": null },
  { "label": "Tone", "dd1": "Neutral", "dd2": null },
];

const merge_value = (key, current_value, new_value) =>
  (key === 'label' || !current_value) ? new_value :
    !new_value ? current_value :
      [].concat(current_value, new_value);

const merge_objects = (object1, object2) =>
  Object.entries(object2).reduce(
    (acc, [key, value]) => Object.assign(acc, { [key]: merge_value(key, object1[key], value) }),
    {}
  );

const mapped = data.reduce(
  (acc, item) => acc.set(item.label, merge_objects(acc.get(item.label) ?? {}, item)),
  new Map()
);

const res = [...mapped.values()];

console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

Can you check this?

const cars = [
    {
        "label": "Medium",
        "dd1": "Cat A",
        "dd2": "Non Cision",

    },
    {
        "label": "Medium",
        "dd1": "Cat B",
        "dd2": null,

    },
    {
        "label": "Tone",
        "dd1": "Neutral",
        "dd2": null,

    }
];

function groupBy(objectArray, property) {
    return objectArray.reduce(function (acc, obj) {
        let key = obj[property]
        if (!acc[key]) {
            acc[key] = []
        }
        acc[key].push(obj)
        return acc
    }, {})
}

function sum(a, c) {
    if (a && c) {
        return a + ', ' + c
    } else if (a) {
        return a
    } else if (c) {
        return c
    } else {
        return null
    }
}

let object = groupBy(cars, 'label')
let arr = [];

for (const property in object) {
    arr.push({
        property,
        dd1: object[property].map(o => o.dd1).reduce((a, c) => { return sum(a, c) }),
        dd2: object[property].map(o => o.dd2).reduce((a, c) => { return sum(a, c) })
    })
}


console.log(arr);

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