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

154
Visualizações
How to merge two objects containing same keys but different values

I'm wanting to merge two array that carry objects with the same keys, but one object may have a value, but the other object, carrying the same key, may have a null value. I'm wanting to merge the two to try and replace all the null values and have one final object.

I've written the following, but at the moment, I'm only getting undefined as the final result.

const objectOne = [
  {
    one: null,
    two: "Two",
    three: null
  }
];

const objectTwo = [
  {
    one: "One",
    two: null,
    three: "Three"
  }
];

const compareObjects = (searchKey, searchValue) =>
  objectTwo.map((retrieve) =>
    Object.entries(retrieve).forEach(([retrieveKey, retrieveValue]) => {
      if (!searchValue) {
        objectOne.searchKey = retrieveValue;
        console.log(objectOne);
      }
    })
  );

const newObject = objectOne.map((search) =>
  Object.entries(search).forEach(([searchKey, searchValue]) =>
    compareObjects(searchKey, searchValue)
  )
);

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

0

Reduce seems more useful in this case than forEach. Reduce will build a new thing from the input and return that.

const objectOne = [
  {
    one: null,
    two: "Two",
    three: null
  }
];

const objectTwo = [
  {
    one: "One",
    two: null,
    three: "Three"
  }
];

const merged = objectOne.map((item, idx) => {
  return Object.entries(item).reduce((acc, [key, value]) => {
    acc[key] = value === null && objectTwo.length > idx ? objectTwo[idx][key] : value;
    return acc;
  }, {})
});
console.log(merged);

about 4 years ago · Juan Pablo Isaza Relatório

0

One method you can use is to create a function that combines/merges the two dictionaries. First, we create our newObject:

const newObject = [

]

Then, we create our function using an O(n^2) approach and call it:

combine(objectOne,objectTwo)
console.log(newObject)

function combine(objectOne, objectTwo){
    for (let [key1,value1] of Object.entries(objectOne[0])){
        for (let [key2,value2] of Object.entries(objectTwo[0])){
            if(key1 == key2){
                if(value1 == null){
                    newObject.push({
                        key: key1,
                        value: value2
                    })
                }
                else{
                    newObject.push({
                        key: key1,
                        value: value1
                    })
                }
            }
        }
    }
}

This is the following output:

[
  { key: 'one', value: 'One' },
  { key: 'two', value: 'Two' },
  { key: 'three', value: 'Three' }
]
about 4 years ago · Juan Pablo Isaza Relatório

0

Your mapping of keys/entries is pretty close. It might be easiest to do something like this though:

const objectOnes = [
  {
    one: null,
    two: "Two",
    three: null
  },
  {
     a: 123,
     b: undefined,
  },
];

const objectTwos = [
  {
    one: "One",
    two: null,
    three: "Three"
  },
  {
      b: 456,
  }
];

function merge(a, b) {
    const result = { ...a }; // copy a
    for (const key in result) {
        // Let's say we want to pick the non-null/undefined value
        if (result[key] !== null && result[key] !== undefined) continue;
        result[key] = b[key]; // copy from b
    }
    return result;
}

const merged = objectOnes.map((obj, i) => merge(obj, objectTwos[i]));
console.log(merged);

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