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

111
Views
Obtain the same result with one or more keys in objects

With these objects

let myObjectA = {"fruits": {"item1":1, "item2":1}, "vegetables": {"item3":1, "item4":1} },
    myObjectB = {"fruits": {"item5":1, "item6":1} };

I need to do the same for loop for obtaining the keys, but when I do the same for loop

for(var i in myObjectA){
    print(myObjectA[i]);
  }
  for(var j in myObjectB){
    print(myObjectB[j]);
  }

In the first loop I get the two items, but in the second I get undefined

How do I get the fruits result, even when it is only one key in the object? I need a dynamic for loop because I don't know in advance if I'll get a one or two keyed objects

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It's a typo as mentioned, but for reference, you can also obtain object keys with... wait for it... Object.keys :)

let myObjectA = {
    "fruits": {
      "item1": 1,
      "item2": 1
    },
    "vegetables": {
      "item3": 1,
      "item4": 1
    }
  },
  myObjectB = {
    "fruits": {
      "item5": 1,
      "item6": 1
    }
  };

let keys = Object.keys(myObjectA);
console.log(keys);

keys.forEach(k => {
  let item = myObjectA[k];
  let subkeys = Object.keys(item);
  console.log(`subkeys of ${k}`, subkeys)
})

about 4 years ago · Juan Pablo Isaza Report

0

You are passing i in myObjectB[i]

for(var i in myObjectA){
    print(myObjectA[i]);
  }
  for(var j in myObjectB){
    print(myObjectB[j]); // correction pass j not i
  }
about 4 years ago · Juan Pablo Isaza Report
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!