title: Using Knockout mapping for complex JSON
body: <p>Most of Knockout seems very intuitive. One thing that is strange to me though is how the mapping plugin works. I was expecting/hoping I would be able to feed it JSON from an ajax call, and have a sort of "dynamic" view model that is available to reference in my HTML.</p>
  
  <p>The <a href="http://knockoutjs.com/documentation/plugins-mapping.html" rel="nofollow">description of the mapping plugin</a> even makes it sound like this is how it works:</p>
  
  <blockquote>
    <p>"If your data structures become more complex (e.g. they contain
    children or contain arrays) this becomes very cumbersome to handle
    manually. What the mapping plugin allows you to do is create a mapping
    from the regular JavaScript object (or JSON structure) to an
    observable view model."</p>
  </blockquote>
  
  <p>But it appears you actually need to define the view model first in your code, and then you can populate it after the fact using the mapping plugin and some JSON data. Is this right?</p>
  
  <p>A concrete example of what I was trying to do. </p>
  
  <p>I am trying to use Knockout with Solr (a search engine that returns JSON search results). The skeleton structure of the JSON data returned by Solr is:</p>
  
  <pre><code>  {
        "responseHeader": {
            "status": 0,
            "QTime": 0,
            "params": {
                "facet": "true",
                "facet.field": "System",
                "q": "testphrase",
                "rows": "1",
                "version": "2.2"
            }
        },
        "response": {
            "numFound": 0,
            "start": 0,
            "maxScore": 0.0,
            "docs": []
        },
        "facet_counts": {
            "facet_queries": {},
            "facet_fields": {
                "System": []
            },
            "facet_dates": {},
            "facet_ranges": {}
        },
        "highlighting": {}
    }
  </code></pre>
  
  <p>In fact, that's the structure I am feeding into my mapped view model when I first set it up.</p>
  
  <p>Just so you understand a bit about how the JSON data comes back from Solr: The response.docs array contains an array of hashes, where the hash data is comprised of key/values for your indexed document data. Each hash in the array is one document being returned in your search results. </p>
  
  <p>That part seems to map over just fine. </p>
  
  <p>The "highlighting" part of the JSON is what causes me problems. When I try to reference the highlighting fields in my HTML, I get ReferenceErrors. Here's an example of what the highlighting field might look like in the JSON:</p>
  
  <pre><code>"highlighting": {
      "2-33-200": {
          "Title": ["1992 &lt;b&gt;Toyota&lt;/b&gt; Camry 2.2L CV Boots"]
      },
      "2-28-340": {
          "Title": ["2003 &lt;b&gt;Toyota&lt;/b&gt; Matrix 2.0L Alignment"]
      },
      "2-31-2042": {
          "Title": ["1988 &lt;b&gt;Toyota&lt;/b&gt; Pickup 2.4L Engine"]
      }
  }
  </code></pre>
  
  <p>I have a foreach in my HTML that tries to parse through each response.docs element, and if the highlighting part of the object contains a match for that document's Id field, I want to substitute the highlighted Title rather than the default Title. (In the code below, "Results" is the name of the viewmodel I am mapping the JSON over to.)</p>
  
  <pre><code>&lt;div id="search-results" data-bind="foreach: Results.response.docs"&gt;
      &lt;div data-bind="attr: { id: 'sr-' + Id }" class="search-result"&gt;
          &lt;h3 class="title"&gt;&lt;a data-bind="html: (($root.Results.highlighting[Id]['Title'] != undefined) ? $root.Results.highlighting[Id]['Title'] : Title), attr: {href: Link}"&gt;&lt;/a&gt;&lt;/h3&gt;
          &lt;span class="date" data-bind="text: DateCreated"&gt;&lt;/span&gt;
          &lt;span class="snippet" data-bind="html: Snippet"&gt;&lt;/span&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>When I try to use this, I always get this error:</p>
  
  <pre><code>Uncaught Error: Unable to parse bindings.
  Message: TypeError: Cannot read property 'Title' of undefined;
  Bindings value: html: (($root.Results.highlighting[Id]['Title'] != undefined)  ? $root.Results.highlighting[Id]['Title'] : Title), attr: {href: Link}
  </code></pre>
  
  <p>I've tried variations on how I am referencing the data, but I just can't seem to access it.</p>
  
  <p><strong>Edit</strong> I'm making a bit of headway. In my mapping definition, I now specify "highlighting" like this:</p>
  
  <pre><code>"highlighting": ko.observable({})
  </code></pre>
  
  <p>Rather than just setting highlighting to {}. Now I am at least able to peer a bit into the highlighting data when I do my mapping. Yet I'm still seeing strange errors.</p>
  
  <p>I've simplified my test HTML code to just spit out the highlighting data for each search result:</p>
  
  <pre><code>&lt;div id="search-results" data-bind="foreach: Results.response.docs"&gt;
      &lt;pre data-bind="text: JSON.stringify(ko.toJS($root.Results.highlighting()[Id()]), null, 2)"&gt;&lt;/pre&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>This returns multiple <code>&lt;pre&gt;</code> tags now that look like this:</p>
  
  <pre><code>{
    "Title": [
      "1992 &lt;b&gt;Toyota&lt;/b&gt; Camry 2.2L CV Boots"
    ]
  }
  </code></pre>
  
  <p>However, if I change that HTML code to this:</p>
  
  <pre><code>&lt;pre data-bind="text: $root.Results.highlighting()[Id()]['Title']"&gt;&lt;/pre&gt;
  </code></pre>
  
  <p>I continue to get errors like this:</p>
  
  <pre><code>Message: TypeError: Cannot read property 'Title' of undefined;
  Bindings value: text: $root.Results.highlighting()[Id()]['Title']
  </code></pre>
  
  <p>Makes no sense to me! My previous test shows that the data available does contain a "Title" key, why can't I access that data?</p>
  
  <p><strong>Edit</strong> I created <a href="http://jsfiddle.net/dWQfP/5/" rel="nofollow">a jsfiddle</a>, but of course... it works as expected. I am unable to reproduce my issue on jsfiddle. :-(</p>
  
  <p><strong>Edit</strong> OK I am making some headway here, but am still very confused as to what is going on. First I changed my debugging HTML to this:</p>
  
  <pre><code>&lt;div id="search-results" data-bind="foreach: Results.response.docs"&gt;
      &lt;pre data-bind="text: console.log($root.Results.highlighting()[Id()])"&gt;&lt;/pre&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I then submitted my ajax call, and I noticed in the Chrome console this output:</p>
  
  <pre><code>undefined
  undefined
  &gt; Object
  </code></pre>
  
  <p>So for some reason, the <code>foreach</code> loop is looping over 3 Results.response.docs, and the first two are not mapping to anything in my highlights() object, so they are returning undefined -- and that's why my attempt to pull the .Title property was failing.</p>
  
  <p>To confirm this, I wrapped a <code>ko if: $root.Results.highlighting()[Id()]</code> around that block, and was finally able to access the .Title property during the foreach loop without a JS error.</p>
  
  <p>This still leaves me with the question of why/how there are 3 Results.response.docs objects being looped over. Perhaps the foreach binding is being run 3 times, and the first 2 times the highlighting object is empty, and the third time, it's finally filled in? But I am having a hard time figuring out why that would be.</p>
  
  <p>Another possible clue: if I trigger the ajax call a second time, without reloading the page, I can see that those 3 "passes" all return a valid Object each time in the console log. So instead of two <code>undefined</code>s and an Object, it's three Objects all in a row. </p>
  
  <p>On my HTML output, though, I only see one row of data. So that seems to prove that it's not looping over 3 elements, but is in fact being run 3 times. The question remains... WHY?</p>