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

175
Visualizações
How to send Object with properties which exist ? JS

I need to object to server but need to format

example of object ->

let obj = 
{
 id: 1,
 title: title
}

This is okay butt any time i got different property

I need to format if I got name property i need to replace instead title

if i got name i need to format object

let obj = 
{
 id: 1,
 name: name
}

Title property i got always but when i got name i need to replace...

i am try with:

if(name){
 return name: name
} else {
return title: title
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can create a function to do it:

function createObj(id, s, isName = false){
    let obj = {id: id};
    if(isName){
        obj.name = s;
    } else {
        obj.title = s;
    }
    return obj;
}

You can then call that function like this:

let o1 = createObj(1, 'Person', true); // {id: 1, name: 'Person'}
let o2 = createObj(2, 'CEO', false); // {id: 2, title: 'CEO'}

console.log(o1); // Outputs: {id: 1, name: 'Person'}
console.log(o2); // Outputs: {id: 2, title: 'CEO'}
about 4 years ago · Juan Pablo Isaza Relatório

0

I think you can do this with the hasOwnProperty(prop) function.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Have a look at the attached code:

// consider a list of objects
// some objects contain the property 'title'
// while the rest of them have the property 'name'
let objects =
[
    {
        id: 1,
        title: "it is title"
    },
    {
        id: 2,
        name: "it is name"
    }
]


// iterate through each object
// and replace its 'name' property 
// with the 'title' property
objects.forEach(obj => {

    // does object has the property 'name'?
    // if yes, replace it with the property 'title'
    if(obj.hasOwnProperty('name')){
      
      // set value of the property 'title'
      obj.title=obj.name;
      
      // delete the property 'name'
      delete obj.name;
    }
})

// log all objects for testing
objects.forEach(obj => {
  console.log(obj.id, obj.title)
})
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