javascript - 对象过滤的嵌套数组在 JS 中返回 undefined
问题描述
我正在尝试为每个产品检查标签对象数组是否至少有一个节目标签。
const allProducts = this.products.forEach(product =>
product.tags.some(item => item.tagName !== 'shows'),
)
数据样本:
Products: [
{
productId:...
productName: ...
tags:[
{
tagId:...
tagName:...
}
{
tagId:...
tagName:...
}
]
},
{
productId:...
productName: ...
tags:[
{
tagId:...
tagName:...
}
{
tagId:...
tagName:...
}
]
}
]
似乎在 some() 之后它不起作用。出了什么问题,如何解决?
解决方案
首先, forEach
不返回任何东西。所以你应该.filter
改用。
对于每个产品,检查对象的标签数组是否至少有一个节目标签。
其次,条件应该是,===
而不是!==
,此外,need return the true if all products are passing the some() not filter
==> 解决方案:
const allValidProducts = this.products.filter(product => product.tags.some(item => item.tagName === 'shows'));
const result = allValidProducts.length === this.products.length;
如您所见,.some
工作正常。
const array = [1, 2, 3, 4, 5];
console.log(array.some(element => element % 2 === 0));
// expected output: true
推荐阅读
- android - 如何在 Android 的 Razorpay 中指定自定义付款方式
- python - Flask-limiter - 如何找到 Flask-limiter 在 Redis 中存储的键名
- java - Lists.addAll(Map.get(key)),无意中改变了`Map`
- java - I don't understand how this line works: "System.out.println("\nCard: " + Deck.get(number).getValue() + " of " + Deck.get(number).getSuit() );"
- javascript - Express POST 无法识别字符串
- airflow - 如何从 Apache Airflow 调用外部服务器(在每次 DAG 运行之后)
- python-3.x - 用python3中的正则表达式匹配句子中的变体名称字符串
- azure - Azure ARM 模板 - 如何引用更改的资源参数
- c# - AddDelegate addDelegate = new AddDelegate(Add); 有什么区别?和 AddDelegate addDelegate = 添加;
- android - 单元测试列表扩展功能 - Kotlin