我想知道如何检查这个。 例如:
var products = [
{
title: 'Product 1',
categories: ['One', 'Two', 'Three']
},
{
title: 'Product 2',
categories: ['Three', 'Four']
}
];
var categories = ['Two','Four'];
如何让两种产品与其中一种产品相匹配? 希望有人可以帮助我:))
答案 0 :(得分:7)
products.filter(function(product) {
return categories.some(function(cat) {
return product.categories.indexOf(cat) >= 0;
});
});
_.filter(products, function(product) {
return _.some(categories, function(cat) {
return _.indexOf(product.categories, cat) >= 0;
});
});
答案 1 :(得分:0)
使用简单的for
:
var products = [
{
title: 'Product 1',
categories: ['One', 'Two', 'Three']
},
{
title: 'Product 2',
categories: ['Three', 'Four']
}
];
var categories = ['Two', 'Four'];
var list = []
for (x in products) {
for (y in products[x].categories) {
if (categories.indexOf(products[x].categories[y]) != -1) {
list.push(products[x].title)
}
}
}
console.log(list) //here your match
答案 2 :(得分:0)
从代码方面来说不是很好的解决方案,但它可以很明确(如果有人不理解)并且它的工作
var products = [
{
title: 'Product 1',
categories: ['One', 'Two', 'Three']
},
{
title: 'Product 2',
categories: ['Three', 'Four']
}
];
var categories = ['Two','Four'];
var retArr = [];
for (i = 0; i < categories.length; ++i) {
for (j = 0; j < products.length; ++j) {
if(products[j].categories.indexOf(categories[i]) > -1){ // check if product categories contains some category. If yes, then add to array
retArr.push(products[j]);
}
}
}
console.log(retArr);
&#13;
答案 3 :(得分:0)
简单地循环:
var foundproducts = [];
for (i = 0; i < products.length; i++) {
for (u = 0; u < categories.length; u++) {
if (products[i].categories.indexOf(categories[u]) != -1) {
foundproducts.push(products[i].title);
break;
}
}
}