简体   繁体   中英

How to get iterate JSON object and JSON array using JavaScript .forEach

I have the following JSON object:

var json = {"tsn": {
    "settings": 
        {"app_name": "TSN",  "version": "1.0"}, 
    "occurrences": 
        ["Party", "Music"]
    }
};

I really don't understand why I can't access its values like this:

json.tsn.forEach(function(item){
    console.log(item.settings.app_name);
    console.log(item.occurrences);
});

I get json.tsn.forEach is not a function .

forEach is a method available for arrays; it does not exist for non-array objects.

In fact, you don't need to iterate for what you are doing. Just do this:

var item = json.tsn;
console.log(item.settings.app_name);
console.log(item.occurrences);

Alternatively, you can use Object.keys to get an array of keys, and then you can continue like this:

Object.keys(json.tsn).forEach(function(key){
    var item = json.tsn[key];
    console.log(item);
});

Or even Object.entries to get key/value pairs:

Object.entries(json.tsn).forEach(function([key, item]){
    console.log(key, item);
});

The forEach method isn't part of the Object specification .

To iterate through enumerable properties of an object, you should use the for...in statement.

var json = {
    "tsn": {
        "settings": {
            "app_name": "TSN",
            "version": "1.0"
        },
        "occurrences": ["Party", "Music"]
    }
};

for (var prop in json) {
    console.log(json[prop].settings.app_name);
    console.log(json[prop].occurrences);
}

See for...in statement reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM