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
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
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.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) andfind 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