Knockout.js js-在数组散列中循环一个数组
My rails应用程序正在向我的页面发送一个大型JSON结构,其中包含如下元素:Knockout.js js-在数组散列中循环一个数组,knockout.js,Knockout.js,My rails应用程序正在向我的页面发送一个大型JSON结构,其中包含如下元素: "nutrient_contributions": { "Vitamin K": [ [ "Broccoli (raw)", "92.46 mcg" ], [ "ginger - ground", "0.04 mcg" ] ], "Vitamin B-6": [ [ "pepper - cayenne"
"nutrient_contributions": {
"Vitamin K": [
[
"Broccoli (raw)",
"92.46 mcg"
],
[
"ginger - ground",
"0.04 mcg"
]
],
"Vitamin B-6": [
[
"pepper - cayenne",
"0.13 mg"
],
[
"ginger - ground",
"0.03 mg"
]
]
}
使用knockout,我只想将其中一个散列元素转换为HTML表。在下面的示例中,带有'text:display_nutrient'
的th呈现为维生素B-6
;我认为我应该能够使用display\u作为散列键,这是错误的吗
%table
%thead
%tr
%th{colspan: 2, data: { bind: 'text: display_nutrient' }}
%tr
%th Ingredient Name
%th Nutrient Value
%tbody{data: { bind: 'foreach: $root.recipe().nutrient_contributions()[display_nutrient]()' }}
%tr
%td{data: { bind: 'text: shift()' }}
%td{data: { bind: 'text: shift()' }}
使用javascript控制台,我可以看到我的数据不是像简单的JSON那样加载,而是被转换成一个对象
> window.my_recipe_view_model.recipe().nutrient_contributions()
Object {Vitam B-6: function, Vitamin K: function…}
> window.my_recipe_view_model.recipe().nutrient_contributions()['Vitamin K']()
[
Array[2]
0: "Broccoli (raw)"
1: "92.46 mcg"
length: 2
__proto__: Array[0]
,
Array[2]
0: "ginger - ground"
1: "0.04 mcg"
length: 2
__proto__: Array[0]
]
因此,百万美元的问题是-我做错了什么?如果您的
display\u
属性是一个ko.observable
,那么您需要在foreach
绑定表达式中展开它,并将其作为函数调用:
data-bind='foreach: $root.recipe().nutrient_contributions()[display_nutrient()]()'
注意显示后的()
演示:如果您的display\u
属性是一个ko.observable
属性,则需要在foreach
绑定表达式中将其展开,并将其作为函数调用:
data-bind='foreach: $root.recipe().nutrient_contributions()[display_nutrient()]()'
注意显示后的()
演示:如果你的显示营养素是一个可观察的ko.
你需要写:'foreach:$root.recipe().nutrient\u contributions()[display\u nutrient()](),
注意显示营养素之后的额外(
。就这样!我知道这是件愚蠢的事。如果你把这个作为一个答案而不是一个评论,我会把它标记为正确的……如果你的显示营养素是一个ko.observable
你需要写:'foreach:$root.recipe().nutrient\u contributions()[display\u nutrient()](显示营养素())
注意显示营养素
之后的额外。就这样!我知道这是件愚蠢的事。如果你把它作为答案而不是评论,我会把它标记为正确的。。。。