title: Knockout JS initializing observable array from server data using a javascript type
body: <p>I'm looking for the best way to initialize a knockout observable array from some server data (ViewBag), and I want the array contents to be of a javascript type I have defined. Without the requirement of the JS type I could just use:</p>
  
  <pre><code>materialVarieties: ko.observableArray(@Html.Raw(Json.Encode(ViewBag.Materials)))
  </code></pre>
  
  <p>but I also have a material JS type that I want to use so I can have some extra ViewModel specific properties and functions i.e.:</p>
  
  <pre><code>var material = function(id, name) {
      this.id = id;
      this.name = name;
      this.selected = ko.observable(false);
  
      this.select = function()
       {
          jQuery.each(processViewModel.materials(), function(index, item)
          {
              item.selected(false);
          });
          this.selected(true);
        }
  }
  </code></pre>
  
  <p>And then the required initialization becomes:</p>
  
  <pre><code>materialVarieties: ko.observableArray([new material(1, "Apricot"), .....
  </code></pre>
  
  <p>Currently I build up a string from the ViewBag data and then render that as the initializer like this:</p>
  
  <pre><code>@{ var items = string.Join(",",
                  ((IEnumerable&lt;MaterialVariety&gt;) ViewBag.Materials)
                              .Select(m =&gt; string.Format("new material({0}, {1})",
                                        Json.Encode(m.Id), Json.Encode(m.Name)))); }
  
  var processViewModel = {
      material: ko.observableArray([@Html.Raw(items)])
  </code></pre>
  
  <p>But I'm wondering if there is a cleaner way than the <code>string.Join</code> bit. I could wrap it up in a Helper. What do you do?</p>