最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Feb 19, 2017 at 15:27 NiceroNicero 4,3877 gold badges32 silver badges57 bronze badges 3
  • because forEach is array method and json.tsn is an object not array – charlietfl Commented Feb 19, 2017 at 15:29
  • do you really need a loop? Or just do console.log(json.tsn.settings.app_name)? – charlietfl Commented Feb 19, 2017 at 15:32
  • Yes, I do need a loop because this is the output of an API which has a lot more data. – Nicero Commented Feb 19, 2017 at 15:39
Add a ment  | 

2 Answers 2

Reset to default 4

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.

发布评论

评论列表(0)

  1. 暂无评论