Update item in ko.ObservableArray

I have a small question that i want to find one item by its property and i want to update the same item , also it should reflect in collection.

I am not using knockout util library.

 Choice = function (id, text, order, selected) {
            this.Text = ko.observable(text);
            this.ID = ko.observable(id);
            this.Order = ko.observable(order);
            this.Selected = ko.observable(selected);
        },
Question = function (questiontext, id, order) {
            this.QuestionName = ko.observable(questiontext);
            this.QuestionId = ko.observable(id);
            this.QuestionOrder = ko.observable(order);
            this.Choices = ko.observableArray([]);
            this.UserResponse = ko.observable();
            this.Inputs = ko.observable(new Input());
        },

i want to find question no 3 and i want to update items choice information and added to Questions.

Any help on this.

Answers


Assuming questions refers to the ObservableArray which contains the list of Questions on your view model:

function find(array, predicate) {
    array = ko.utils.unwrapObservable(array);
    for (var i = 0; i < array.length; i++)
        if (predicate(array[i]))
            return array[i];
}

var question = find(questions, function (q) { return q.QuestionId == 3; });
var choices = question.Choices;
// Update, add or do anything with `choices`

Things you might want to do after:

  • Add an argument to specify the context in which the predicate runs.
  • Add an argument to specify the index to start the search at.
  • Create pseudo-arrays for your collections and augment their prototypes with the function, using this instead of the first argument.
  • Optimize for performance (limit lookups).
  • Implement a findAll variant that returns an array of all matches.
  • Think about using a third-party library to help with all of this until these kinds of features get standardized. Some third-party libraries are very good with all of this; it really depends on how extensively you'll need to manipulate these structures. Don't add a dependency for no reason, but don't burden yourself either by reinventing the wheel when it's not the component's goal.

Edit: Typo -- should mention I didn't run the code, please don't copy-paste blindly.


Need Your Help

how to tell which project a .cpp file is in

c++ visual-studio

I took over a C++ code which is in a solution. That one solution contains many projects. I edit a .cpp file, but can't file which project it belongs to, so I don't know which project to build. Buil...

Regex to find the href from anchore tag for specific cases in c# .net

c# .net regex

I have some specific cases for which regex does not fit.