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

138
Visualizações
merge two JavaScript objects and keep method definitions

Suppose I have a javascript class:

class SomeClass {
  constructor() {
    this.field1 = [];
    this.field2 = 0;
    this.field3 = "somestring";
  }

  someMethod(param1) {
    // do some magical stuff
  }
}

At some point I have a need to merge two objects, one of them is of SomeClass type.

const obj1 = new SomeClass();

const obj2 = {
    field1: [1, 2, 3],
    field2: [3, 4, 5],
    field3: "other string"
}

const mergedObj = {...obj1, ...obj2};

Now I have lost the someMethod method in mergedObj variable, throwing a TypeError:

mergedObj.someMethod("amazingparam"); //=> Uncaught TypeError: mergedObj.someMethod is not a function

How can I keep the method definitions?

Edit

To be more clear: I would like to create a new object, keep the obj1 and obj2 as they were.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could use Object.assign it will merge it for you but this will mutate your first object so to solve that problem you could create a clone of you first object on the fly using Object.create like this

class SomeClass {
  constructor() {
    this.field1 = [];
    this.field2 = 0;
    this.field3 = "somestring";
  }

  someMethod(param1) {
    console.log('hello')
    // do some magical stuff
  }
}

const obj1 = new SomeClass();

const obj2 = {
    field1: [1, 2, 3],
    field2: [3, 4, 5],
    field3: "other string"
}

let mergedObj = Object.assign(Object.create(obj1), obj2);

mergedObj.someMethod('')

about 4 years ago · Juan Pablo Isaza Relatório

0

From Josephs answer I worked out a solution.

class SomeAmazingClass{
    constructor() {
        this.var1 = "";
        this.var2 = "";
    }

    someMethod() {
        return this.var1 + this.var2;
    }
}

function mergeToSomeAmazingClass(obj1, obj2) {
    return Object.assign(new SomeAmazingClass(), obj1, obj2);
}

let a1 = new SomeAmazingClass();
a1.var1 = "OldVar1"
a1.var2 = "OldVar2"
a1.newVar3 = "Yay"

let a2 = {
    var1: "NewVar1"
}

let merged = mergeToSomeAmazingClass(a1, a2);
console.log(merged.someMethod());

This keeps the method definitions and keeps the input objects from mutating. Looks a little clumsy, but if there is a better solution I would be happy to see that.

Edit

Updated the merge function.

about 4 years ago · Juan Pablo Isaza Relatório

0

Simply make your constructor accept optional parameters:

class SomeClass {
  constructor({field1 = [], field2 = 0, field3 = "somestring"}) {
    Object.assign(this, {field1, field2, field3});
  }

  someMethod(param1) {
    // do some magical stuff
    console.log('SomeClass instance here');
  }
}

const obj2 = {
    field1: [1, 2, 3],
    field2: [3, 4, 5],
    field3: "other string"
}

const obj1 = new SomeClass(obj2);

obj1.someMethod();

console.log(obj1);

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