javascript - lodash 过滤器在 Shopify 订单的多维数组中找不到值
问题描述
在处理之前查看订单 line_item 是否已退款...
这是一个订单:
var order = {
line_items: [
{
id: 1326167752753
}
],
refunds: [
{
refund_line_items: [
{
id: 41264152625,
line_item_id: 1326167752753,
}
]
}
]
};
尝试注销过滤结果:
console.log(
_.filter(order, {
refunds: [
{
refund_line_items: [
{
line_item_id: 1326167752753
}
]
}
]
}).length
);
我要0
上控制台了。
在这种情况下我使用 _.filter 错误吗?
解决方案
您可以在 lodash 中使用some
andfind
并在 ES6 中轻松执行此操作:
var order = { line_items: [{ id: 1326167752753 }], refunds: [{ refund_line_items: [{ id: 41264152625, line_item_id: 1326167752753, }] }] };
// lodash
const _searchRefunds = (lid) => _.some(order.refunds, x =>
_.find(x.refund_line_items, {line_item_id: lid}))
console.log('loadsh:', _searchRefunds(1326167752753)) // true
console.log('loadsh:', _searchRefunds(132616772323232352753)) // false
//es6
const searchRefunds = (lid) => order.refunds.some(x =>
x.refund_line_items.find(y => y.line_item_id == lid))
console.log('ES6:', searchRefunds(1326167752753)) // true
console.log('ES6:', searchRefunds(132616772323232352753)) // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
推荐阅读
- java - 如何通过代码为netbeans中的微调器设置最大值?
- delphi - 带有 Delphi 10.3 的控制台应用程序中的 Tcomport
- android - 在 onSaveInstanceState() 中保存对象
- spring-boot - BeforeSaveEventHandler 中的删除操作将持久化数据刷新到 DB
- reactjs - 产品列表状态在编辑时未显示更新的产品
- python - 如何在 Keras 中连接三层的一部分?
- sql - SAP HANA:有没有办法将模式和表名定义为过程的输入参数?
- ios - Swift - 表格视图中的单元格出现在另一个单元格上
- c++ - 模板类型推导警告返回对本地临时对象的引用
- node.js - 如何在 Web 应用程序中集成外部依赖项