我有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
答案 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]);
}