【问题标题】:lodash filter not finding value in multidimensional array of Shopify orderlodash 过滤器在 Shopify 订单的多维数组中找不到值
【发布时间】:2018-10-26 22:31:42
【问题描述】:

在处理之前查看订单 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 是不是错了?

【问题讨论】:

  • _.filter 的第二个参数是一个谓词函数。请参阅文档here,但您的第二个参数不是谓词函数。
  • 您要在order.line_itemsorder.refunds 上过滤什么?

标签: javascript arrays lodash shopify


【解决方案1】:

函数take 需要一个数组(order 不是数组,order.refunds 是)和一个谓词,而不是一个对象。

无论如何,我会用Array.some写它:

const itemWasRefunded = order.refunds.some(refund =>
  refund.refund_line_items.some(refund_line_item =>
    refund_line_item.line_item_id === 1326167752753
  )
);

或者,或者,获取所有 line_item_ids 并检查包含:

const itemWasRefunded = _(order.refunds)
  .flatMap("refund_line_items")
  .map("line_item_id")
  .includes(1326167752753);

【讨论】:

    【解决方案2】:

    您可以使用 somefind 并在 lodash 中执行此操作,也可以在 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>

    【讨论】:

    • 为什么在谓词中使用find?另一个some 可以。
    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2018-07-07
    • 2019-11-20
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多