2017-03-15 63 views
0

任何人都可以給我一個正確的解決方案,這個program.how使用foreach循環打印所有的值。我試過,但我得到一個錯誤,因爲未定義的值預先感謝...我在等待答覆...在nodejs中使用循環訪問json元素

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

回答

1

您可以如下使用forEach

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

爲您快速的回覆非常感謝兄弟是工作完美... – vigneshRavi

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

+0

三江源先生.... – vigneshRavi