node.js jade - 无法访问嵌套数组元素

时间:2011-09-06 17:21:35

标签: node.js pug

很抱歉,如果这是一个非常基本的问题,但我找不到任何类似于我想要解决的问题的例子。

有人可以解释为什么我无法访问以下代码中的嵌套数组元素以及如何访问该数组中的元素?从下面的json,我无法获得从第二个结果中找到的“Items”数组。

正在返回以下json:

{
    "d": {
        "results": [
            {
                "__metadata": {
                    "uri": "...",
                    "type": "..."
                },
                "__index": 1,
                "ID": "someID1",
                "Name": "Some Name 1"
            },
            {
                "__index": 2,
                "Items": [
                    {
                        "__metadata": {
                            "uri": "...",
                            "type": "..."
                        },
                        "ID": "itemID2_1",
                        "Name": "Item 2_1"
                    }
                ]
            },
            {
                "__index": 3,
                "Items": [
                    {
                        "__metadata": {
                            "uri": "...",
                            "type": "..."
                        },
                        "ID": "itemID3_1",
                        "Name": "Item 3_1"
                    }
                ]
            },
            ...

以下是玉石布局:

- var results=records, col_type='even';
table#results(style="border-collapse:collapse;")
  tr
    th.result-header Index
    th.result-header ID
    th.result-header Name
  - each r in results
    - col_type=col_type=='even' ? 'odd' : 'even'
    tr.result-row
      - if (!r.Items)
        td(class='result-col-'+col_type,style="border-left:1px solid black")
          #{r.__index}
        td(class='result-col-'+col_type,style="border-left:1px solid black")
          #{r.ID}
        td(class='result-col-'+col_type,style="border-left:1px solid black")
          #{r.Name}
      - else
        td(class='result-col-'+col_type,style="border-left:1px solid black")
          #{r.__index}
        - each i in r.Items
          td(class='result-col-'+col_type,style="border-left:1px solid black")
            #{i.ID}
          td(class='result-col-'+col_type,style="border-left:1px solid black")
            #{i.Name}

2 个答案:

答案 0 :(得分:0)

这里的问题是你的JSON采用这种格式

{
  "d": { 
     "results": [
        ...
      ]

因此您需要在

中更改jade模板中的此部分
- each r in results
  - col_type=col_type=='even' ? 'odd' : 'even'

到此,

- each r in results['d']['results']
  - col_type=col_type=='even' ? 'odd' : 'even'

这样,你的循环将遍历每个数组项。

答案 1 :(得分:0)

所以我遇到了同样的问题。我的解决方法是:

- each r in results
  - each i in r.Items
     "... do stuff with i"