SP_
SP_

Reputation: 391

Parsing JSON in JS and comparing key values

I have a JSON data

{
"FrontLeft"  : "FALSE",
"FrontRight" : "FALSE",
"RearLeft"   : "FALSE",
"RearRight"  : "TRUE"  }

I read this data from a text file using AJAX and parsed .

function loadDoc() 
   {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

      var arrLines = xhttp.responseText;
      alert ( arrLines);
      var obj = JSON.parse(arrLines);
     /*
        Need to compare values of each key
      */


    }
  };

How can access values of each key ???

Upvotes: 1

Views: 50

Answers (2)

ladar
ladar

Reputation: 5876

You can use for loop:

for (var key in p) {
 if (p.hasOwnProperty(key)) {
  console.log(key + " -> " + p[key]);
 }
} 

Or you can use Object.keys(), see MDN documentation:

var obj = { 'FrontLeft' : '1', 'FrontLeft1' : '2' };
var keys = Object.keys(foo); // ['FrontLeft', 'FrontLeft1'] 

Another way could be possibly for-of but it does not have wide browser support yet see MDN documentation

Upvotes: 0

Jeff P Chacko
Jeff P Chacko

Reputation: 5018

You can access the values in the object like this,

obj.FrontLeft     //this will give you "FALSE"
obj.FrontRight    //this will give you "FALSE"

or obj['FrontLeft'] will also give you the same result.

Upvotes: 1

Related Questions