0

I have an observable sizeDetails in knockout and i need to get the length in knockout template. My observable is below

sizeDetails: ko.observable()

On Ajax call success i have set observable as below

  self.sizeDetails({sizeGuideDetails: sizeGuideDetails,
                    shopBySizeDetails: shopBySizeDetails
                  });

How to get sizeGuideDetails and shopBySizeDetails length seperately in knockout template

Pavithra
  • 129
  • 1
  • 2
  • 13

3 Answers3

0

Since the keys themselves are objects, we have to get their lengths like this.

This is more about JavaScript in general than Knockout. To get the value of a Knockout observable, you call it like a function. e.g.: sizeDetails(). In this case it would return the object, and then we can get individual sizes and return them in an array or whatever format suits you.

function getSizeDetails(){
    const sizeDetailsObject = self.sizeDetails();
    let sizes = [];
    for (var key in sizeDetailsObject) {
        //check if key exists
        if (sizeDetailsObject.hasOwnProperty(key)) {
            //since key is sure to be an object, get its length like this:
            sizes.push(Object.keys(sizeDetailsObject[key]).length);
        }
    }
    return sizes;
};

You could also create a pure Computed observable, whose value updates automatically when sizeDetails gets updated.

self.sizes = ko.pureComputed(function(){
    const sizeDetailsObject = self.sizeDetails();
    let sizes = [];
    for (var key in sizeDetailsObject) {
        if (sizeDetailsObject.hasOwnProperty(key)) {
            sizes.push(Object.keys(sizeDetailsObject[key]).length);
        }
    }
    return sizes;
}, self);

Now you can always get the latest sizes by calling self.sizes().


To get their sizes individually, you can do as Erick and Bivo have mentioned in their answers.

Ray
  • 3,864
  • 7
  • 24
  • 36
0

Try with

<div data-bind="html: sizeDetails().sizeGuideDetails.length"></div>
<div data-bind="html: sizeDetails().shopBySizeDetails.length"></div>
0

sizeDetails().sizeGuideDetails.length or sizeDetails().sizeGuideDetails().length depending on whether sizeGuideDetails is an observable or not. Same with shopBySizeDetails.

You can use it anywhere you like it in html like:

<span data-bind="text: sizeDetails().sizeGuideDetails().length">

or without any html tags:

<!-- ko if: sizeDetails().sizeGuideDetails().length > 0 -->

some html if the condition is true

<!-- /ko -->

Bivo Kasaju
  • 1,143
  • 3
  • 13
  • 28