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

99
Visualizações
Typescript/Javascript Conditionally Add members to object using spread op

I am trying to conditionally add members to an object using the method prescribed here

Here is my code:

const theobj = {
    field1: "hello",
    field2: 1,
    data: {
        datafield1: "world",
        datafield2: 2
    },
    field3: "yowzee"
};

let someobj: any;
someobj = theobj;

const test = {
    ...(someobj.field1 &&  {field1: someobj.field1}),
    ...(someobj.nofield && {nofield: "yowzee"}),
    ...(someobj.data?.datafield1 && {data: {dataField1: "woohoo"}}),
    ...(someobj.data?.datafield2 && {data: {datafield2: "hooahh"}}), // overwrites the above   
};

console.log(test);

This works great except that the last conditional overwrites data.datafield1. Its as if it re-creates the inner data objects. Any ideas how to resolve this?

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

0

In that last line, you're setting the data property of the object to a new object, {datafield2: "hooahh"}.

That would be the equivalent of:

{
  data: { a: 1 }
  data: { b: 2 }
}

duplicate keys are overriden, so it becomes

{
  data: { b: 2 }
}

If you want to set data to a single object with conditional sub-keys of its own, you can do:

const test = {
    ...(someobj.field1 &&  {field1: someobj.field1}),
    ...(someobj.nofield && {nofield: "yowzee"}),
    ...(someobj.data && {data: {
        ...(someobj.data.datafield1 && {dataField1: "woohoo"}),
        ...(someobj.data.datafield2 && {dataField2: "hooahh"}),
    }}),
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Yes, it's happening exactly what you're thinking, this is why you need a reference from a previous value of the data object.

const test = {
    ...(someobj.field1 &&  { field1: someobj.field1 }),
    ...(someobj.nofield && { nofield: "yowzee" }),
    ...(someobj.data.datafield1 && { data: { dataField1: "woohoo" }}),
    ...(someobj.data.datafield2 && { data: { ...someobj.data, datafield2: "hooahh" }}), // doesn't overwrites the above.
};

By spreading someobj.data inside of itself, you are ensuring that it has his previous value.

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