Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda