使用nodejs

时间:2017-03-15 15:49:53

标签: json node.js for-loop

任何人都可以给我一个正确的解决方案这个程序。如何使用foreach循环打印所有值。我试过但我得到一个错误,因为未定义的值提前谢谢...我等待回复......

differ.json:


{
"table":
[
   {
      "place":
      {
        "STATE":"TAMILNADU",
        "DISTRICT":"VELLORE"
      }
   },
  {
    "place":
    {
      "STATE":"KERALA",
      "DISTRICT":"ALAPHUZHA"
    }
  },
  {
    "place":
    {
      "STATE":"ANDHRA PRAADESH",
      "DISTRICT":"KUNTUR"
    }
  }
]
}
Nodejs file:

var fs = require('fs');
var obj1 = fs.readFileSync('differ.json', 'utf8');
var data=JSON.parse(obj1);
var countobjects = Object.keys(data).length;
console.log(countobjects);
for( var place in data.table)
{
    for( var field in data.table[place])
    {
        console.log("State:" + data.table[place].field);
        console.log("District:" + data.table[place].field);
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用forEach,如下所示:

data.table.forEach(function(element){
  console.log(element.place.STATE);
  console.log(element.place.DISTRICT);
})

答案 1 :(得分:0)

您应该使用of而不是in作为循环,并且可以使用ES6字符串模板文字进行简化,如此...



const data = { "table": [{ "place": { "STATE":"TAMILNADU", "DISTRICT":"VELLORE" } }, { "place": { "STATE":"KERALA", "DISTRICT":"ALAPHUZHA" } }, { "place": { "STATE":"ANDHRA PRAADESH", "DISTRICT":"KUNTUR" } }] }

for (const d of data.table) {
  const s = `State: ${d.place.STATE}\nDistrict: ${d.place.DISTRICT}`
  console.log(s)
}