在knockout.js中访问多维数组中的特定项

时间:2015-11-21 14:34:07

标签: javascript multidimensional-array knockout.js

我试图弄清楚如何在多维数组中获取嵌套数组的0索引。我使用foreach绑定将状态和城市列为<ul>。我目前的代码是:

http://codepen.io/ntibbs/pen/vNMKzg?editors=101

<ul id='list' data-bind="foreach: states">
<li>
    <div>Surf locations in
        <span data-bind="text: name"> </span>:
    </div>
    <ul data-bind="foreach: city">
        <li>
            <span data-bind="text: $data"> </span>
        </li>
    </ul>
</li>
</ul>


var state = function(name, city) {
    this.name = name;
    this.city = ko.observableArray(city);
}
var viewModel = {
    states: [
        new state("Virginia", [["Va Beach",[36.852926, -75.977985]], ["Chincoteague Island",[37.933179, -75.378809]]]),
        new state("Maryland", [["Atlantic City",[39.364283, -74.422927]], ["Ocean city",[38.336503, -75.084906]]]),
        new state("North Carolina", [["Oakacroke",[35.114615, -75.98101]], ["Nags Head",[35.957392, -75.624062]],["Emerald Isle",[34.677940, -76.950776]]])
        ]
};

ko.applyBindings(viewModel);

我当前的代码显示了lon,lat和城市名称,但我只想列出城市名称

1 个答案:

答案 0 :(得分:2)

您可以在绑定中使用数组索引器,这样就可以使用$data[0]访问第一个索引:

 <ul data-bind="foreach: city">
     <li>
         <span data-bind="text: $data[0]"> </span>
     </li>
 </ul>

工作CodePen

更多视图模型导向的方法是创建一个适当的城市&#34;具有name属性的对象:

var City = function(data) {
  this.name = data[0];
  this.coords = data[1];
}

在创建City时使用此state

var state = function(name, city) {
    this.name = name;
    this.city = ko.observableArray(city.map(function(c){ return new City(c)}));
}

你的绑定看起来像这样:

<ul data-bind="foreach: city">
    <li>
        <span data-bind="text: name"> </span>
    </li>
 </ul>

示例CodePen