4

I have this code:

var id = event.target.getAttribute('id');

var matchedItem = ko.utils.arrayForEach(self.ProductEffectImagesToMatch(),
  function(item) {
    if (item.index == id) {
      return item;
    }
  }
);

I want to get the item by index in the array, if index matches the id then return the item.

How can that be done correctly?

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Laziale
  • 7,965
  • 46
  • 146
  • 262

2 Answers2

2

"ko.utils." is unnecessary. If "self.ProductEffectImagesToMatch" is an observable array, then "self.ProductEffectImagesToMatch()" returns ordinary array, that you can filter by predicate:

var matchedItem = self.ProductEffectImagesToMatch().filter(function (item) {
    return item.index == id;
})[0];

[0] returns undefined in case of empty result, the first matching item otherwise.

Update

If you want to get n-th element of an array, you can use "id" as index:

matchedItem = self.ProductEffectImagesToMatch()[id];
TSV
  • 7,538
  • 1
  • 29
  • 37
  • I'm getting item.index is undefined although with console.log I can see that objects exist https://i.gyazo.com/60f7ee65b860546a1e045236cea322a3.png – Laziale Feb 26 '16 at 08:50
  • @Laziale - what is the structure of object inside "self.ProductEffectImagesToMatch()" collection? – TSV Feb 26 '16 at 08:52
  • 1
    Of course, there is no "index" ptoperty in this object. If you want to get n-th element of an array, you can use "id" as index "matchedItem = self.ProductEffectImagesToMatch()[id];" – TSV Feb 26 '16 at 09:06
  • you're correct, thanks, please update your answer so I can mark as correct answer – Laziale Feb 26 '16 at 09:15
  • should prefer using ko.unwrap instead of using ProductEffectImagesToMatch() – Saransh Kataria Feb 26 '16 at 09:21
  • `ko.utils.arrayForEach()` is a utility method to accommodate that do not support the array utility functions natively. This has been more common in the early days of knockout, but they still officially support [IE down to version 6](http://knockoutjs.com/documentation/browser-support.html) - and that's because they have these fill-in functions. Bottom line, they are a valid way to do this. – Tomalak Feb 26 '16 at 09:21
1

You can use for it ko.utils.arrayFirst if there should be only one item and arrayFilter if few.

var matchedItem = ko.utils.arrayFirst(self.ProductEffectImagesToMatch(), function (item) {
    return item.index == id;
});
Viktor Kukurba
  • 1,360
  • 9
  • 14
  • I'm getting item.index is undefined although with console.log I can see that objects exist https://i.gyazo.com/60f7ee65b860546a1e045236cea322a3.png – Laziale Feb 26 '16 at 08:50