javascript - How to return an item from an observable array by property - Stack Overflow

I have this code: var id = event.target.getAttribute('id');var matchedItem = ko.utils.arrayFo

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?

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?

Share Improve this question edited Feb 26, 2016 at 9:53 Tomalak 339k68 gold badges546 silver badges635 bronze badges asked Feb 26, 2016 at 8:22 LazialeLaziale 8,24548 gold badges155 silver badges271 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

"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];

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;
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745434290a4627536.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信