user1400915 user1400915 - 6 months ago 12
HTML Question

Data bind over in array in knockoutjs

I have an array as follows:

self.arrayObj : Array[2]
>0:Object
>Display1
->InnerObjects
>__proto
>1:Object
>Display2
-->InnerObjects


My interntion is to display "Display1" and "Display2" which are strings
I am doing the html binding as follows:

<div data-bind="foreach: self.arrayObj">
<span data-bind="text:$data[0]"></span>
</div>


How can I iterate over the array and display only texts?

Answer

I would like to answer my own question.

It is not a simple thing when we want to bind the object with dynamic keys and values in the UI using Knockout js. If we have the fixed keynames then its easy. What I did was , converted the json object to 2-D array :

In the .js file

var 2Darray = jsonObject.map(function(val) { 
     var keyname = Object.keys(val)[0];
     var value = val[keyname];
     return [keyname,value];
});

In the html file , we can bind it two times in a loop:

<div data-bind:"foreach:2Darray">

  <div data-bind:"foreach: $data">

   <div data-bind:"text:$data[0]">
   <div data-bind:"foreach: $data[1]">
     <div data-bind:"text:$data.val">
      </div>
   </div>
 </div>