Home > Software engineering >  Obtain the same result with one or more keys in objects
Obtain the same result with one or more keys in objects

Time:12-01

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

CodePudding user response:

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)
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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
  }
  • Related