0

我有 3 个可观察的数组,如下所示:

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

我想比较数组 a 和数组 b 以及在哪里

数组 a === 数组 b.ID

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

4

2 回答 2

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/

于 2013-09-18T09:11:17.937 回答
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]);
}
于 2013-09-18T09:11:21.260 回答