Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!