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

103
Visualizações
Return dynamically populated object literal in javascript

A little new to JS. It seems to me something like this would be possible, but after spending a few hours of getting nowhere, I'm wondering if there actually is a way to make something like this work. It's just a function that returns an object, but the key values are set in the function instead of being passed to it:

function makeProduct() {
      return {
          Id: '0',
          Name: document.getElementById('Name').value,
          Price: document.getElementById('Price').value,
          Category: document.getElementById('Category').value
      };
    }

It seems like this would save a lot of duplicate code, instead of having to get the user input, assign it to variables, and then populate the object with the more proper syntax:

function product(id, name, price, category) ...

I was able to accomplish what I was trying to do with a class, but it does generate a lot more code. If you had a large object, you are typing a lot of the same things multiple times.

I do have some code that works using jquery, but if I try and put it in a function that returns the object, it errors out on me, too.

The whole point of the code is to call the function, return the object, and use Axios to send it to my webAPI.

async function makeGetRequest() {

  var product = makeProduct();

let res = await axios.post('http://localhost:56730/api/product/', product);

let data = res.data;
console.log(data);
}

And it does work as expected with my class.

Also, because of the keywords in this question, this is something really hard to search for and get relevant answers.

about 4 years ago · Juan Pablo Isaza
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