knockout.js observableDictionary complex hash

648 Views Asked by At

I implemented observableDictionary within my project. I have a fairly complex hash, but am unsure how to access keys.

What if I had the following dictionary and wanted to get the hair color?:

var person = {
   name: ‘Joe Bloggs’,
   height: 180,
   hair: {
      color: ‘brown’,
      length: ‘long’
   }
}

Based on the github examples, I would assume it would be similar to this:

<div data-bind=”foreach: person.items”>
   <div data-bind=”if: hair”>
     <div data-bind=” foreach: value.items”>
          <span data-bind=”text: $data.color”></span>
      </div>
   </div>
</div>

Any help would be greatly appreciated.

1

There are 1 best solutions below

0
tcigrand On

You could do it a couple of different ways

1.With this you can access all keys and values of the nested object

<div data-bind="foreach: person.items">
   <div data-bind="if:key()=='hair'">
     <div data-bind="foreach: value().items">
           <div>
               <span data-bind="text:key"></span>
               <span data-bind="text:value"></span>
           </div>
      </div>
   </div>
</div>

With

var person = {
   name: 'Joe Bloggs',
   height: 180,
   hair: new ko.observableDictionary({
      color: 'brown',
      length: 'long'
   });
};

2.If you only want to get the hair color property, this might be easier

<div data-bind="foreach: person.items">
   <div data-bind="if:key()=='hair'">
          <span data-bind="text: value().color"></span>
   </div>
</div>

With

var person = {
   name: 'Joe Bloggs',
   height: 180,
   hair: {
      color: 'brown',
      length: 'long'
   }
};