0

can anyone give me a correct solution for this program.how to print all values using foreach loop.I tried but I got an error as undefined values Thanks in advance...I am waiting for reply...

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 Answers 2

1

You can use forEachas below :

data.table.forEach(function(element){
  console.log(element.place.STATE);
  console.log(element.place.DISTRICT);
})
Sign up to request clarification or add additional context in comments.

Comments

0

You should be using of instead of in for your loop, and it can be simplified using ES6 string template literals like so...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.