skip to Main Content

I have the following json object and trying to iterate with jQuery each but it only returns one iteration. What am I not doing right?

var data = "{
  "SIEcat4": {
    "3001": {
      "test": "test",
      "test": "test"
    },
    "3300": {
      "test": "test",
      "test": "test"
    }
  },
  "SIEcat5": {},
  "SIEcat6": {},
  "SIEcat13": {
    "3990": {
      "test": "test",
      "test": "test"
    }
  }
}"




$(JSON.parse(data)).each(function(key, value) {
  console.log("test");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

2

Answers


  1. In your question your JSON object is wrapped in a string, that’s not right. If you have a string representation of an object you will have to parse that as a separate step. If you have a real JSON object then you can use Object.keys to iterate over the keys of that object.

    Also, jQuery is not needed at all for this.

    Here’s how you can loop over the keys and data in an object

    var data = {
      "SIEcat4": {
          "3001": {
              "test": "test",
              "test": "test"
          },
          "3300": {
              "test": "test",
              "test": "test"
          }
      },
      "SIEcat5": {},
      "SIEcat6": {},
      "SIEcat13": {
        "3990": {
            "test": "test",
            "test": "test"
        }
      }
    };
    
    Object.keys(data).forEach(key => {
      console.log(key, '=>', data[key]);
    });

    If your data is a string representation of JSON data you can do the exact same thing as above, but you will need to run JSON.parse over it first to get the data out of the string.

    var dataAsString = `{
      "SIEcat4": {
          "3001": {
              "test": "test",
              "test": "test"
          },
          "3300": {
              "test": "test",
              "test": "test"
          }
      },
      "SIEcat5": {},
      "SIEcat6": {},
      "SIEcat13": {
        "3990": {
            "test": "test",
            "test": "test"
        }
      }
    }`;
    
    var data = JSON.parse(dataAsString);
    
    Object.keys(data).forEach(key => {
      console.log(key, '=>', data[key]);
    });
    Login or Signup to reply.
  2. To elaborate on my comment

    $jQueryCollection.each() is normally used for jQuery collections – I would not use it for a nested object

    $.each can be used for objects but only one layer

    Also you have the same quotes wrapping the object and quoting the data. Newlines are only allowed in JS in a template literal or when you escape the newlines. So change the outer " to ` (bactick) and

    find how to iterate nested object

    Lastly your object is invalid since it has more than one key named the same

    Here is a working recursive iterator on a valid object – it can be used in jQuery if you insist

    const obj = JSON.parse(data);
    const iterateObject = (obj, parentKey = '') => {
      for (let key in obj) {
        if (typeof obj[key] === 'object') {
          iterateObject(obj[key], `${parentKey}${key}.`);
        } else {
          console.log(`${parentKey}${key}: ${obj[key]}`);
        }
      }
    };
    
    iterateObject(obj);
    
    console.log('n------n');
    
    // jQuery .each also needs the iterator
    let parentKey = '';
    $.each(obj, function(key, value) {
      if (typeof obj[key] === 'object') {
        iterateObject(obj[key], `${parentKey}${key}.`);
      } else {
        console.log(`${parentKey}${key}: ${obj[key]}`);
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <script>
      var data = `{
      "SIEcat4": {
        "3001": {
          "test1": "test",
          "test2": "test"
        },
        "3300": {
          "test1": "test",
          "test2": "test"
        }
      },
      "SIEcat5": {},
      "SIEcat6": {},
      "SIEcat13": {
        "3990": {
          "test1": "test",
          "test2": "test"
        }
      }
    }`; 
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search