循环javascript对象来打印数据

时间:2017-02-21 16:49:50

标签: javascript loops nested javascript-objects traversal

我有一个javascript对象,我想根据1个常见类别遍历和打印数据。

Javascript对象:

var $states = {
"AL" : {
  "longname": "Alabama",
  "lawOne": "Alabama Law 1",
  "lawTwo": "Alabama Law 2",
  "lawThree": "Alabama Law 3",
  "region" : "Southeast"
},
"AK" : {
  "longname": "Alaska",
  "lawOne": "Alaska Law 1",
  "lawTwo": "Alaska Law 2",
  "lawThree": "Alaska Law 3",
  "region" : "Northwest"
},
"AZ" : {
  "longname": "Arizona",
  "lawOne": "Arizona Law 1",
  "lawTwo": "Arizona Law 2",
  "lawThree": "Arizona Law 3",
  "region" : "Southwest"
},
etc...
}

我也可以循环数组,并获得控制台记录同一区域中所有状态的细粒度:

for (var key in $states) {
        if ($states.hasOwnProperty(key)) {
            var $getStateRegion = $states[key].region

            if ($getStateRegion === "Northeast") {
                console.log ($states[key].longname);
            }
        }
    }

一旦我尝试遍历那些并打印一个表格,那么我遇到的问题就是这个数据。我希望能够在那里输入一个长名,lawOne,lawTwo和lawThree值。是什么赋予了?一旦我尝试运行for循环,这就是我遇到障碍的地方。提前谢谢!

2 个答案:

答案 0 :(得分:0)

尝试下面的工作代码。

var $states = {
"AL" : {
  "longname": "Alabama",
  "lawOne": "Alabama Law 1",
  "lawTwo": "Alabama Law 2",
  "lawThree": "Alabama Law 3",
  "region" : "Southeast"
},
"AK" : {
  "longname": "Alaska",
  "lawOne": "Alaska Law 1",
  "lawTwo": "Alaska Law 2",
  "lawThree": "Alaska Law 3",
  "region" : "Northwest"
},
"AZ" : {
  "longname": "Arizona",
  "lawOne": "Arizona Law 1",
  "lawTwo": "Arizona Law 2",
  "lawThree": "Arizona Law 3",
  "region" : "Southwest"
}
};

var result = {};
Object.keys($states).forEach(function(key) {
  if ($states[key]["region"] === "Southwest") {
    result[key] = $states[key];
  }
});
console.log(result);

答案 1 :(得分:0)

你走在正确的轨道上。在继续之前,我想指出你正在使用for..in循环,但是新版本的Javascript也支持for..of循环,所以这是你可能想要考虑的事情。不同之处在于for..in循环为您提供了对象的键,而for..of循环为您提供了值,因此它通过跳过您写入某些内容的步骤来缩短代码:

for( var index in array ){
  var currentObject = array[ index ];
}

解决方案的秘诀在于如何处理DOM,有很多方法可以做到这一点。我会告诉你一个,但它不一定是最快或最好的。我建议玩不同的DOM操作来找到最适合你的那个。

首先,我们知道如何获取记录,因此循环的javascript方面,你已经处理了......

接下来,我们需要创建表格....我假设你想根据你的描述想要四列,但是你可以很容易地调整它以在每一行上放置州名和一个法则,这可能是更好的设计允许不同数量的法律。

html看起来像这样:

<table>
    <tr><th>State</th><th>Law 1</th><th>Law 2</th><th>Law 3</th></tr>
    <!-- Here is where we would create new html for each state -->
</table>

然后你的循环需要通过创建几行显示为:

来添加到此html
<tr><td>[State]</td><td>[Law1]</td><td>[Law2]</td><td>[Law3]</td><tr>

我们将使用DOM的字符串操作,因为它是一个很好的起点,因为它与您手写的内容最相似。

我们将把桌子分成三个部分:标题,正文和页脚。

var header = "<table><tr><th>State</th><th>Law 1</th><th>Law 2</th><th>Law 3</th></tr>";

var body   = ""; //this is where we add the data

var footer = "</table>";

现在,在循环中,我们将根据需要创建每一行并将其添加到正文中:

for( var index in stateObj ){
      ...error checking occurs here...
      var state = stateObj[ index ];
      var stateColumn = "<td>" + state.longname + "</td>";
      var law1Col = "<td>" + state.lawOne + "</td>";
      var law2Col = "<td>" + state.lawTwo + "</td>";
      var law3Col = "<td>" + state.lawThree + "</td>";
      var row = "<tr>" + stateColumn + law1Col + law2Col + law3Col + "</tr>";
      //now that we have a row, we add it to the body
      body += row;  //same as body = body + row;
}

在我们拥有了身体后,我们可以通过组合标题,正文和页脚来制作我们的表格:

var tableHTML = header + body + footer;

然后我们找到一个将它注入我们文档的地方:

var outputDiv = document.getElementById( "stateTableData" );
outputDiv.innerHTML = tableHTML;

这是一个实例:

var states = {
  PA: {
    longname:"Pennsylvania",
    lawOne:"It is illegal to sing in the shower in apartment buildings within the city limits of Philadelphia",
    lawTwo:"All motorists are required to stop the vehicle for passing horsemen. The vehicle shall be covered with camoflage so as not to scare the horses.",
    lawThree:"Any house having more than four women occupants shall be considered a brothel and shall be in violation of the law."
},
  NJ: {
      longname:"New Jersey",
      lawOne:"There is no such thing as the Mafia",
      lawTwo:"Any reference to the denizens of New Jersey shall be derogatory and degrading, think Jersey Shore",
      lawThree:"There is no escape from New Jersey and we are not a suburb of NYC"
      },
  VA: {
      longname:"Virginia",
      lawOne: "Civil War re-enactments must have the North as the victor.",
      lawTwo: "All roads shall end in Richmond, VA",
      lawThree: "I have run out of silly ideas for this example."
  }
};
function buildTableForState( stateNames ){
    var stateList = stateNames.split(",");
    
    //remove spaces
    for( var i in stateList ){ stateList[i] = stateList[i].trim(); }
    
    //initialize table parts
    var header = "<table><tr><th>State</th><th>Law 1</th><th>Law 2</th><th>Law 3</th></tr>";
    var footer = "</table>";
    var body = "";
    
    //build body
    for( var index in states ){
       if( stateList.indexOf( index ) !== -1 ){
            var currentState = states[index];
            body += buildRowForState( currentState );
       }
    }
    
    //compose and inject table
    var tableHTML = header + body + footer;
    var documentOut = document.getElementById( "outputDiv" );
    documentOut.innerHTML = tableHTML;
}

function submitTable(value){
    buildTableForState( value );
}

function buildRowForState( currentState ){
    var state = makeTableCol( currentState.longname );
    var law1 = makeTableCol( currentState.lawOne );
    var law2 = makeTableCol( currentState.lawTwo );
    var law3 = makeTableCol( currentState.lawThree );
    var row = makeTableRow( [state, law1, law2, law3] );
    return row;
}

function makeTableCol( stringText ){
  return "<td>" + stringText + "</td>";
}

function makeTableRow( arrayColumns ){
  return "<tr>" + arrayColumns.join("") + "</tr>";
}
<h1>Table Loader</h1>
<form>
  <p>Use the values "PA", "NJ", and "VA" to generate a table. You can use more than one value by separating them with a comma.</p>
  <input type="text" id="stateNames" name="stateNames" /><br/>
  <button onclick="submitTable(stateNames.value);">Build Table</button>
  <p>Try:
  </p>
  <ul>
  <li>PA</li>
  <li>NJ,VA</li>
  <li>VA,PA,NJ</li>
  </ul>
</form>

<h1>Table Output appears here</h1>
<div id="outputDiv"></div>

注意:关于实时代码,HTML大于显示框。在我的浏览器中,我必须向下滚动snippit HTML以查看生成的表。或者将snippit窗口扩展为完整选项卡以在更大的屏幕中查看它。

上面的代码是简化的,大多数编码器会告诉你不要使用HTMLElement.innerHTML,因为它很慢,但它是一个很好的起点。一旦完成此操作,请开始使用document.create(tagName)进行练习,然后使用更直接的DOM操作。