1

I'm trying to figure out how to get the 0 index of a nested array in a multidimensional array. I'm using a foreach binding that lists the states and cities to a <ul>. My current code is:

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);

My current code is showing the lon, lat and the city names, but I only want list the city names tho

1 Answer 1

2

You can use array indexers in your bindings, so you can access the first index with $data[0]:

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

Working CodePen

A more view model oriented approach would be to create a proper "city" object which has a name property:

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

And use this City when creating a state:

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

And your binding could look like this:

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

Sample CodePen

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. I would have sworn I tried that already. It works, thanks. I'll accept your answer asap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.