0

I'm trying to loop through an object's values which in turn are objects of there own with data that I want to retrieve. I'm trying to get the data that matches a variable that is created dynamically, not a hard-coded path. The only solutions I can find are for objects that have data attached at the top level not nested in another object. Below is a simple version of my problem. Thank you in advance.

const VMs = {
  'VM01': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM02': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM03': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  }
};

const thisVM = 'VM03'; // Hardcoded here but actually this.$route.params.data (data not defined in this example)

for (let obj in VMs) {
  console.log(obj) // this is only a string of the key eg "VM01". I 
  // want obj to be an object where I can reference its data.

  if (obj = thisVM) {

    // get data from this VM

  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

0

I am not really sure what's your intents, but if you want to acces the nested props, you can use Object.entries method, like that:

const VMs = {
  'VM01': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM02': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM03': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  }
};

const thisVM = 'VM03';

Object.entries(VMs).forEach(([prop, val]) => {
  console.log(val) 
  if (prop === thisVM) {
    // Your action
  }
})

If the depth of the nesting is bigger or unknown, it is better to use recursive traversing.

HynekS
  • 2,738
  • 1
  • 19
  • 34
0

Use VMs[obj] to get the object.

Your if statement has a typo, = should be == to perform a comparison.

But there's little need for the loop in the first place. You can just use VMs[thisVM] to get the specific object you want. See Dynamically access object property using variable

const VMs = {
  'VM01': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM02': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM03': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  }
};

const thisVM = 'VM03'; // Hardcoded here but actually this.$route.params.data (data not defined in this example)

for (let obj in VMs) {
  console.log(VMs[obj]) // this is only a string of the key eg "VM01". I 
  // want obj to be an object where I can reference its data.

  if (obj == thisVM) {

    // get data from this VM

  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612