Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to display multi dimentional ko observable array data in html. But, i didn't get output.

My code :

<!-- ko if: ($parent.cust_opt_avail() === 1) -->
<!-- ko foreach: $parent.customVal() -->
<div class="product-custom-option-select">
    <p class="options-label" data-bind="text:key"></p>
    <p class="options-label" data-bind="text:custom_option_select_text"></p>
</div>
<!-- /ko -->
<!-- /ko -->

cust_opt_avail() is ko observable variable. customVal is ko observable array.

output of customVal is :

enter image description here

I want to display custom_option_select_text and display key name on first p tag.

How to do it ?

Expected Result :

enter image description here

please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
267 views
Welcome To Ask or Share your Answers For Others

1 Answer

From your previous question and comments in this question, I gather you're setting an object to ko.observableArray(). This is not correct. You should set a customVal to a ko.observable(). Then use Object.keys() and use aliasing in your foreach binding.

var viewmodel = function() {
  var self = this;
  self.cust_opt_avail = ko.observable(1);
  
  let customVal = {
    Color: [{'custom_option_select_text': 'Red + $200.00'}, 
            {'custom_option_select_text': 'Green + $250.00'}],
    Size: {'custom_option_select_text': 'XL + $150.00'}
  };
  
  // This should be an observable
  self.customVal = ko.observable(customVal);
};

ko.applyBindings(new viewmodel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: (cust_opt_avail() === 1) -->
<div data-bind="foreach: { data: Object.keys(customVal()), as: 'key' }">
  <div class="product-custom-option-select">
    <p style="font-weight:bold" data-bind="text:key"></p>

    <!-- ko if: Array.isArray($parent.customVal()[key]) -->
    <!-- ko foreach: $parent.customVal()[key] -->
       <p class="options-label" data-bind="text:custom_option_select_text"></p>
    <!-- /ko -->
    <!-- /ko -->
  
  <!-- ko if: !Array.isArray($parent.customVal()[key]) -->
  <p class="options-label" 
    data-bind="text:$parent.customVal()[key].custom_option_select_text"></p>
  <!-- /ko -->
</div>
</div>
<!-- /ko -->

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...