0

I have the following code:

j = 1;
while (j < 50) {
  //requirement:
     console.log(JSONitem [j]["criteria"]);
     reqtest = Object.keys(JSONitem [j]["criteria"]);
         ....
     j++;
}

But when I execute this, I get the following error:

TypeError: JSONitem[j] is undefined

The output object from the console.log part is right, but also in this line is the TypeErro above. I think, the "j" does not replace the number, but in the output console it works...

Thanks!

  • 1
    What does your json look like? – Nagaraju Apr 15 '17 at 12:08
  • Your first line will return an error `while (j = 1; j < 50) {` should be `var j = 1; while (j < 50) {` – Mohamed Abbas Apr 15 '17 at 12:12
  • That's not [JSON](http://json.org/) (nor a JSON item) but a regular object: [What is the difference between JSON and Object Literal Notation?](http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Apr 15 '17 at 12:15

1 Answers1

0
console.log(...JSONitem.map(el=>el.criteria));

Your code may behaves unexpected if the length of your array (?) changes. You should use the Array.prototype methods or the for..in, for..of or

for(i=0;i<array.length;i++) 

loops to iterate over your Array.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • JSONitem.map does not work, because I have an object, not an array: `{"display":{"description":"","background":""},"criteria":{impossible":{}}` I simply want to get all criterias in "criteria". And it should work with object.keys but the "j" were not replaced with an number or something like this. But thanks! – KaiAlexander Apr 15 '17 at 12:24