比较2个可观察数组并使用knockout将匹配值推送到第3个数组

时间:2013-09-18 09:03:24

标签: javascript jquery arrays knockout.js

我有3个可观察的数组,看起来像:

a [1,3]
b [ {"ID": 1, "Val": "Value1"}, {"ID":2, "Val":"Value2"}, {"ID":3, "Val":"Value3"}]
c []

我想将数组a与数组b和

进行比较
  

数组a === array b.ID

我想将数组b的整个值推入c

2 个答案:

答案 0 :(得分:2)

您可以结合使用forEach循环和indexOf功能:

function VM() {
    var self = this;
    self.a = ko.observableArray([1, 3]);
    self.b = ko.observableArray(
    [{
        "ID": 1,
            "Val": "Value1"
    }, {
        "ID": 2,
            "Val": "Value2"
    }, {
        "ID": 3,
            "Val": "Value3"
    }]);
    self.c = ko.observableArray([]);

    ko.utils.arrayForEach(self.b(), function (item) {
        if (self.a.indexOf(item.ID) != -1) {
            self.c.push(item);
        }
    });

}

这是工作小提琴:http://jsfiddle.net/UhSYE/

答案 1 :(得分:1)

//function to find items in an array
var indexOf = function(needle){
    if(typeof Array.prototype.indexOf === 'function')
    {
        indexOf = Array.prototype.indexOf;
    }
    else
    {
        indexOf = function(needle){
            var i = -1, index = -1;

            for (i = 0; i < this.length; i++)
            {
                if (this[i] === needle)
                {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle);
};

var a = [1, 3],
    b = [{"ID": 1, "Val": "Value1"}, {"ID":2, "Val":"Value2"}, {"ID":3, "Val":"Value3"}],
    c = [];

//loop through `b` and check each item's ID then push it to `c`
for (var i = 0; i < b.length; i++)
{
    if (a.indexOf(b[i].ID) !== -1) c.push(b[i]);
}