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

215
Vistas
Javascript object returning {} when filling

I was taking an online assessment, and I cannot figure out why my original solution in JS was not working. My first solution is contained in the top two function calls. No matter what, it returned an empty object {}. When I copy and pasted the function body from findOrderQuantity into allCandyOrders, it worked just fine.

function findOrderQuantity(candyObject) {
  if (candyObject.inStock < candyObject.weeklyAverage) {
    return 2 * candyObject.weeklyAverage;
  } else {
    return 0;
  }
  return 0;
}


function allCandyOrders(inventory) {
  // this function fails, and always returns {}
  let orderSet = {};
  let quantity = 0;
  let name = '';
  for (let i = 0; i < inventory.lengh; i++) {
    // compute how many to order
    quantity = findOrderQuantity(inventory[i]);
    // add candy to object
    // inventory[i].candy is a string containing a candyName
    name = inventory[i].candy;
    orderSet[name] = quantity;
  }

  return orderSet;
}

Working code

function allCandyOrders(inventory) {
  // this function works properly.
  let orderSet = {};
  let value = 0;
  let candyObject = inventory[0];
  for (let i = 0; i < inventory.length; i++) {
    candyObject = inventory[i];
    if (candyObject.inStock < candyObject.weeklyAverage) {
      value = 2 * candyObject.weeklyAverage;
    } else {
      value = 0;
    }
    orderSet[inventory[i].candy] = value;
  }
  return orderSet;
}

I had originally tried to dynamically create the orderSet object using Object.assign, but it didn't work either. Inventory is an array containing candy objects, which has attributes [candy (string), inStock (int), weeklyAverage (int)]. I'm assuming it's some kind of scope issue, but I can't seem to figure it out. Otherwise, I must be missing something about how JS works. Thank you in advance for your help.

Best,

Brian

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