【问题标题】:Iterating through Objects of Objects Javascript?遍历对象Javascript的对象?
【发布时间】:2020-06-22 21:01:34
【问题描述】:

我有这个对象结构,我想遍历它以创建一个包含所有“属性”的节点。所以我想为对象 1、2、5 和 8 创建节点,但不为数组创建节点。我有这段代码,想知道为什么每个响应属性的 Object.keys() 是 [0] 而不是 [2,5] 或 [9,12]?

  const response = {
              '1':{
                   '2':['3','4'],
                   '5':['6','7']
                   },
              '8':{
                   '9':['10','11'],
                   '12':['13','14']
                   },
  };


  for(const property in response){
    if(!response.hasOwnProperty(property)) continue;
    console.log(property) // prints 1 and 8
    g.addNode(property);
    console.log(Object.keys(property)) // [0] instead of [2,5] or [9,12]
    for(const prop in property){ 
      if(!property.hasOwnProperty(prop) || prop === 0) continue;
      console.log(prop)
      g.addEdge(prop,property, {directed:true})
    }
  }

编辑:这个循环有效:)

for(const property in resp){
      g.addNode(property);
       for(const prop in resp[property]){
         g.addEdge(property,prop, {directed:true})
       }
   }

【问题讨论】:

  • 试试console.log(Object.keys(response[property]));和for(const prop in response[property]){

标签: javascript loops object properties key


【解决方案1】:

我已经在字典中遇到了这个确切的问题,你很快就遇到了这个问题,因为一旦你走得更远,调试起来就会变得非常困难。基本上,您正在使用 for..in 循环遍历字典,这并不完全符合您的要求。基本上,您迭代的每个项目(在这种情况下为property)都不是字典的值({'2':['3','4'], '5':['6','7']}),它是一个包含键和值的完整字典项。这对你来说几乎没有用,所以它不是特别有用。您可以做几件事情,其中​​一件仍然使用 forEach,只是有些不同:

Object.keys(response).forEach(function(key) {
    // do your actions here
    // key is your dictionary key (1, 8)
    // response[key] will have your value ({'2':['3','4'], '5':['6','7']})
});

这应该可以工作,您可以将其余代码使用它。

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多