1
votes

I have a json data formatted like this

{
"ITEMS": [
    {
        "option": "one",
        "values": ["A","B","C","D"]
    },
    {
        "option": "two",
        "values": ["E","F","G"]]
    }
]
}

and script code like this

function Item(data) {
    this.option = ko.observable(data.option);
    this.values = ko.observableArray(data.values);
}

var ProductIndexVM = (function() {
  function ProductIndexVM() {

    items = ko.observable();
    filtered_items = ko.observableArray([]);

    selectedItems = ko.computed(function() {

       return ko.utils.arrayFilter(items(), function(item) { 
        // return something using compare
     });
    });


    // after ajax success
    var mappedItems = $.map(result.ITEMS, function(item) { 
      return new Item(item) 
    });
    items(mappedItems);

  }

  return ProductIndexVM;

})();

After successful ajax request data has been mapped into items observable.

The problem is I need to compare filtered_items observableArray with item functions' values observableArray so that if items inside filtered_items match with any one of the item functions' values it will return that or not.
Simplifying whole thing I want to sort out items with only those contains in filtered_items.

As an example if filtered_items have content same as below

["A", "C", "E"]

the output will be

{
"ITEMS": [
    {
        "option": "one",
        "values": ["A","C"]
    },
    {
        "option": "two",
        "values": ["E"]]
    }
]
}


How can I compare that inside selectedItems?

1

1 Answers

0
votes

This really has nothing much to do with knockout, its a simple algorithmic question. Given an array of object and an array of "selected values" how can I filter the former using the latter:

var input = {
  "ITEMS": [
      {
          "option": "one",
          "values": ["A","B","C","D"]
      },
      {
          "option": "two",
          "values": ["E","F","G"]
      }
  ]
}

var filters = ["A","C","E"];

var result = input.ITEMS.map(item => {
   return {
      "option": item.option,
      "values": item.values.filter(value => filters.indexOf(value)>-1)
   }
});

console.log(result);

Now applied to your knockout, just read your observable arrays as you normally would but use the same algorithm as demonstrated above.