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

97
Visualizações
How to add data to object

I am trying to adddata from another object into a new object while also adding new data const addCardData = { ...optIn, cardId, cardName} here optIn already has cardId and cardName so they are getting replaced by new values, how to make an addCardData such that cardId and cardName not be replaced but added to the object or as a sub object? or is there any other better way to do this?

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

0

If your goal is to keep the values from "optIn", you could add them last.

For example:

addCardData =  { 
  cardId, 
  cardName, 
  ...optIn 
};

If your goal is to add both versions of cardId and both versions of cardName, you have two options:

  1. Change the name of cardId and cardName, since an object can only old one attribute with a given name.

For example:

addCardData =  { 
  newCardId: cardId, 
  newCardName: cardName, 
  ...optIn 
};
  1. Add the optIn object as an attribute
addCardData =  { 
  cardId, 
  cardName, 
  optIn
};

Then you can refer to it by addCardData.optIn.cardId.

about 4 years ago · Juan Pablo Isaza Relatório

0

The main goal is just merge? I mean, merge choosing between new data or old data? Here is a sample code showing both cases:


    const cardId = 999;
    const cardName = "Anakin";
    const optIn = {a:123, b:456, cardId:789, cardName:"Skywalker"}
    
    console.log({ ...optIn, cardId, cardName}); // merge applying new data on cardId/cardName
    console.log({ cardId, cardName, ...optIn}); // merge keeping original data on cardId/cardName

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is a way to combine both objects. If any of the properties already exists in optIn it will be changed into an array in addCardData and the new value will then be pushed onto it:

const optIn={a:123,b:456,cardId:789,cardName:"Harry"},cardId=222,cardName="Sally";

const addCardData = {...optIn};
Object.entries({cardId,cardName}).forEach(([k,v])=>{
 (addCardData[k]=Array.isArray(addCardData[k])?addCardData[k]:[addCardData[k]]).push(v)
});

console.log(addCardData);

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