Javascript 过滤掉数据库中没有关联产品的对象元素
我有一个包含类别列表的对象,我想删除products表中没有关联产品的单个元素(类别) 如何循环遍历Javascript 过滤掉数据库中没有关联产品的对象元素,javascript,Javascript,我有一个包含类别列表的对象,我想删除products表中没有关联产品的单个元素(类别) 如何循环遍历cats对象,读取每个元素的catid属性,搜索products表并获得与catid值匹配的所有产品,然后从没有任何产品用于关联类别的原始对象元素中筛选出来 我使用nodejs和knex作为中间件来访问MySQL表。。。但这应该与“如何从对象中过滤某些元素”的问题无关 MyThisCatconsole.log正确跳过没有关联产品的类别,但是NewCAT对象仍然包含所有原始条目。过滤器回调函数需要返
cats
对象,读取每个元素的catid
属性,搜索products表并获得与catid
值匹配的所有产品,然后从没有任何产品用于关联类别的原始对象元素中筛选出来
我使用nodejs和knex作为中间件来访问MySQL表。。。但这应该与“如何从对象中过滤某些元素”的问题无关
My
ThisCat
console.log正确跳过没有关联产品的类别,但是NewCAT
对象仍然包含所有原始条目。过滤器回调函数需要返回true或false。你可以这样做:
const newCats = cats.filter(async (item) => {
const prods = await knex('products').select('prodid').where({ category: item.catid });
if (prods.length > 1){
console.log('ThisCat:', item.catname, ' and LENGTH:', prods.length);
return true;
}
return false;
});
或者只使用if条件:
const newCats = cats.filter(async (item) => {
const prods = await knex('products').select('prodid').where({ category: item.catid });
return prods.length > 1
});
筛选器回调函数需要返回true或false。你可以这样做:
const newCats = cats.filter(async (item) => {
const prods = await knex('products').select('prodid').where({ category: item.catid });
if (prods.length > 1){
console.log('ThisCat:', item.catname, ' and LENGTH:', prods.length);
return true;
}
return false;
});
或者只使用if条件:
const newCats = cats.filter(async (item) => {
const prods = await knex('products').select('prodid').where({ category: item.catid });
return prods.length > 1
});
为什么要在JS而不是SQL中执行此操作?您的具体问题是您的筛选方法是
async
。它总是返回一个真实的承诺。但你真的不应该这样做。它真的很慢。为什么用JS而不是SQL来做呢?你的具体问题是你的过滤方法是async
。它总是返回一个真实的承诺。但你真的不应该这样做。真的很慢。