1

My iteration over the JSON object doesn't work as expected. What's wrong?

function handleResponse(e) {
  var jsonObj = JSON.parse(e.postData.contents);
  console.log("Note=" + jsonObj['Note'] + ", Market=" + jsonObj['Market']);
  // --> "Note=blabla, Market=flowerMarket"

  for (var [key,val] in jsonObj) {
    console.log("Key="+key); 
    console.log("Value="+val);
  }
  // --> "Key=N" "Value=o" "Key=M" "Value=a"
}

The log shows my loop takes only the first letter of the value as whole value and the second letter of the value as key. How do I get the whole key value pairs !?

2 Answers 2

5

In your script of for (var [key,val] in jsonObj) {}, the key is splitted with each character. And, the top 2 characters are retrieved. By this, such result is retrieved. I think that this is the reason of your issue.

If you want to retrieve the values using [key,val] in the for loop, I would like to propose the following modification.

From:

for (var [key,val] in jsonObj) {
  console.log("Key="+key); 
  console.log("Value="+val);
}

To:

for (var [key,val] of Object.entries(jsonObj)) {
  console.log("Key="+key); 
  console.log("Value="+val);
}

References:

1
function handleResponse(e) {
  const jsonObj = JSON.parse(e.postData.contents);
  console.log('Note= %s,Market= %s',jsonObj.Note,jsonObj.Market);
  for(let key in jsonObj) {
    console.log("Key="+key); 
    console.log("Value="+jsonObj[key]);
  }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.