遍历对象以从另一个嵌套对象中检索数据

时间:2018-12-11 19:03:50

标签: javascript object

我试图遍历一个对象的值,这些值又是拥有要检索的数据的对象。我正在尝试获取与动态创建的变量(而不是硬编码路径)匹配的数据。我能找到的唯一解决方案是,对象具有在顶层附加的数据而不嵌套在另一个对象中。以下是我的问题的简单版本。预先谢谢你。

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

  }
}

2 个答案:

答案 0 :(得分:0)

我不确定您的意图是什么,但是如果您想访问嵌套的道具,则可以使用Object.entries方法,如下所示:

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
  }
})

如果嵌套的深度较大或未知,则最好使用递归遍历。

答案 1 :(得分:0)

使用VMs[obj]获取对象。

您的if语句有错字,=应该是==才能进行比较。

但是首先不需要循环。您可以只使用VMs[thisVM]来获取所需的特定对象。参见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

  }
}