node.js jade - Unable to access nested array elements
Sorry if this is a really basic question, but I cannot find any examples similar to the issue I am trying to solve.
Can somebody please explain why I am not able to access a nested array of elements in the following code and also how I can access elements from that array? From the json below, I am not able to get at the "Items" array found from the second result on.
The following json is being returned:
{
"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"
}
]
},
...
Here is the jade layout:
- 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-'开发者_如何学JAVA+col_type,style="border-left:1px solid black")
#{i.ID}
td(class='result-col-'+col_type,style="border-left:1px solid black")
#{i.Name}
The issue here is that your JSON is in this format
{
"d": {
"results": [
...
]
So you need to change this part in your jade template from
- each r in results
- col_type=col_type=='even' ? 'odd' : 'even'
to this,
- each r in results['d']['results']
- col_type=col_type=='even' ? 'odd' : 'even'
This way, your loop will be pass through each array item.
so I just ran across the same problem. My solution was to do:
- each r in results
- each i in r.Items
"... do stuff with i"
精彩评论