Possible Duplicate:
How to loop on a JSON object?
I'm trying to find out how to loop through the attributes of a JSON obj. I can get the attributes by specifying the key (see below), but how do I just loop through all of them?
var jsonStr = '{"Items":[{"Title": "Title 1", "Description":"Description 1"}]}';
var json_parsed = $.parseJSON(jsonStr);
// Cycle through all list items
$.each(json_parsed.Items, function(i, val) {
var listItem = $(this);
var title = listItem.attr('Title');
var description = listItem.attr('Description');
// Instead, loop through all attributes
}
Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.
Looping Using JSON It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values. Here's an example that demonstrates the above concept.
Iterating Over JSON With Root Node Inside your React app, create a data. js file and export the above response as an object. Note that both images and users are arrays, so you can use the map() method in JSX to iterate over them as shown below. You can also use regular for loops.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
for (var name in json_parsed) {
console.log(name + "=" + json_parsed[name]);
}
If you need to check if the corresponding property is defined on the object in question, not on some of those on the prototype chain (this is ridiculous for the case in question, but still useful), you can add this check:
if (json_parsed.hasOwnProperty(name))
console.log(name + "=" + json_parsed[name]);
EDIT
To actually iterate all array objects' attributes, use this snippet:
var items = json_parsed.Items;
for (var i = 0; i < items.length; ++i) {
console.log("Item #" + i);
for (var name in items[i]) {
console.log(name + "=" + items[i][name]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With