knockout.jsknockout-3.0knockout-mvc

Finding the Index Of Argument in ObservableArray - KnockoutJS


I'm newbie on KoJS and my problem is I can't reach my array object's index. I'm trying to check if ID of item is exists, i will increase the amount of item on my shopping cart. I can show my item's on cart view but can't find index of item. I've tried indexOf methods but they returns -1, need help on it. Here is my code part. My data's coming from MVC side. I've tried to find as a id and tried to find as manuel typing id.

function Cart(id, stock_name, stock_id, amount, unit_price, unit_price_tax, unit,
              curr_id, price, rate, product_no, pack_id, tax_rate) {
    return {
        id: ko.observable(id),
        stock_name: ko.observable(stock_name),
        stock_id: ko.observable(stock_id),
        amount: ko.observable(1),
        unit_price: ko.observable(unit_price),
        unit_price_tax: ko.observable(unit_price_tax.toFixed(2)),
        unit: ko.observable(unit),
        curr_id: ko.observable(curr_id),
        price: ko.observable(price),
        rate: ko.observable(rate),
        product_no: ko.observable(product_no),
        pack_id: ko.observable(pack_id),
        tax_rate: ko.observable(tax_rate)
    }
};

self.AddCart = function (d) {
    debugger;

    var index = self.Carts().indexOf('97454');
    var index2 = self.Carts().indexOf(97454);
    if (index !== -1) {
        self.Carts.replace(amount, amount++);
    }
    else {
        self.Carts.push(new Cart(
        d.id,
        d.stock_name,
        d.stock_id,
        d.quantity * 1,
        d.selected_price,
        d.selected_tax_price,
        d.unit,
        d.curr_id,
        d.price,
        d.rate,
        d.product_no,
        d.pack_id,
        d.tax_rate,
    ));
    console.log(self.Carts());
    console.log(self.Carts().length);
}};

Solution

  • Using indexOf always gives you -1 because you're passing it a string (e.g., '97454'), while your Carts array is not an array of strings, but of objects.

    You should use ko.utils.arrayFirst:

    ko.utils.arrayFirst(self.Carts(), function(cart) {
        return cart.id() === '97454';
    })
    

    BTW, I think you don't want an object named Carts, but CartItems.