简体   繁体   English

如何使用 JavaScript .forEach 获取迭代 JSON 对象和 JSON 数组

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

I have the following JSON object:我有以下 JSON 对象:

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 .我得到json.tsn.forEach is not a function

forEach is a method available for arrays; forEach是一种可用于数组的方法; 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来获取一组键,然后您可以像这样继续:

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来获取键/值对:

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

The forEach method isn't part of the Object specification . forEach方法不是Object规范的一部分。

To iterate through enumerable properties of an object, you should use the for...in statement.要遍历对象的可枚举属性,您应该使用for...in语句。

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 .请参阅for...in语句参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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