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
.
-
because
forEach
is array method andjson.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
2 Answers
Reset to default 4forEach
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.