循环访问 Express 中的嵌套对象

iterate over nested objects in express

本文关键字:嵌套 对象 访问 Express 循环      更新时间:2023-09-26

我想知道如何在 express js 中遍历对象。我可以从 json 文件中获取信息,但是一旦我执行循环,它就会一直说它未定义。

我在这里错过了什么,我希望它列出它们。 不过,我将有一个名为 Top 40 的 h2,它将列出 Year.top2011.top40.id.top01 中的所有对象

这里有任何帮助。

我在路由中的索引

lista = JSON.parse(data);
console.log(lista);
res.render('index', {
  lista: lista
});

我的索引在视图中

<% JSON.parse(lista).forEach(function(item) { %>
 <%- item.Year.top2011.top40.id.top01 %>
<% }; %>

我的 JSON 文件

{
"Year": {
"top2011": {
  "top40": {
    "id": {
      "top01": {
        "album_cover": "http://o.scdn.co/image/830a22646bc38f72df95ec98e3ab6bb19aa6074b",
        "artist_namn": "Adele",
        "song": "Rolling In The Deep",
        "spotify": "http://open.spotify.com/track/7h8Ud480Fm4ReUVxgFF9ZX",
        "youtube": "http://youtu.be/rYEDA3JcQqw"
      },
      "top02": {
        "album_cover": "http://o.scdn.co/image/215c999786e8319a09b7af87a970c2bdb6747c92",
        "artist_namn": "LMFAO",
        "song": "Party Rock Anthem",
        "spotify": "http://open.spotify.com/track/1CNJyTUh56oj3OCZOZ5way",
        "youtube": "http://youtu.be/KQ6zr6kCPj8"
      }
    }
  }
}
  }
}
lista不再是

JSON字符串,而是JS对象。这一行:JSON.parse(lista).forEach(function(item)行不通。您需要遍历listalista.forEach(function(item) {})

首先,结构可以改进:·为什么不将前 40 个条目存储在数组中?
此结构包含top40_entries,每个top40数组
内的对象

{"Year": {
    "2011": {
        "top40": [
            {
            "pos": "top01",
            "album_cover": "http://o.scdn.co/image/830a22646bc38f72df95ec98e3ab6bb19aa6074b",
            "artist_namn": "Adele",
            "song": "Rolling In The Deep",
            "spotify": "http://open.spotify.com/track/7h8Ud480Fm4ReUVxgFF9ZX",
            "youtube": "http://youtu.be/rYEDA3JcQqw"
            },
            {
            "pos": "top02",
            "album_cover": "http://o.scdn.co/image/215c999786e8319a09b7af87a970c2bdb6747c92",
            "artist_namn": "LMFAO",
            "song": "Party Rock Anthem",
            "spotify": "http://open.spotify.com/track/1CNJyTUh56oj3OCZOZ5way",
            "youtube": "http://youtu.be/KQ6zr6kCPj8"
            }
        ]
    }
}}

我会使用for循环(需要时):

var top40_2011 = lista.Year.2011.top40; //get the array
for(var i=0; i<top40_2011.length; i++){
    /* Access the values using the keys : */
        //console.log(top40_2011[i].pos);
        //console.log(top40_2011[i].artist_namn);
        //console.log(top40_2011[i].song);
}

注意:请记住,数组从 0 开始,因此 top40 将从 [0] 到 [39];