[英]Json get all nested elements in Javascript
I have a Json structure that I need to run some unit tests on. 我有一个Json结构,需要对其进行一些单元测试。 The structure looks like the following.
结构如下所示。
{
tracks:{
4j38f8-4j39fj-3j4j3j:{
name:"my video track",
mediaType:"VIDEO"
},
280248-248244-ttr24:{
name:"my audio track",
mediaType:"AUDIO"
},
280248-248244-ttr24:{
name:"my audio track",
mediaType:"AUDIO"
}
}
In javascript I have the following code. 在javascript中,我有以下代码。
var data = JSON.parse(jsonFile.json);
if(data.4j38f8-4j39fj-3j4j3j.mediaType == "VIDEO")
{
do something
}
else
{
do something else
}
if(data.4j38f8-4j39fj-3j4j3j.mediaType == "VIDEO")
{
do something
}
else
{
do something else
}
if(data.4j38f8-4j39fj-3j4j3j.mediaType == "VIDEO")
{
do something
}
else
{
do something else
}
However, I do not know how many tracks there will be, and I want to something different depending on what type of track it is. 但是,我不知道会有多少条轨道,并且我希望根据轨道的类型而有所不同。 This leads me to believe that I should iterate through the object.
这使我相信我应该遍历该对象。 Yet because it is not an array, I need to get the key of whatever the next object is inside of a loop.
但是因为它不是数组,所以我需要获取循环内下一个对象的键。 My question is how can I do this?
我的问题是我该怎么做?
For element in tracks
{
if element.mediaType = video
{
do one thing
}
else
{
do another thing
}
}
By using a for..in
structure: 通过使用
for..in
结构:
for (var key in data.tracks) {
if (data.tracks.hasOwnProperty(key)) {
if (data.tracks[key].mediaType === 'VIDEO') {
// do one thing
} else {
// do another thing
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.