首页 > 解决方案 > 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 错误吗?

标签: javascriptarrayslodashshopify

解决方案


您可以在 lodash 中使用someandfind并在 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>


推荐阅读