Lodash过滤器在Shopify订单的多维数组中找不到值。

5

希望在处理之前查看订单行项目是否已退款...

这是一个单独的订单:

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 的第二个参数是一个谓词函数。请参阅此处的文档,但是您的第二个参数不是一个谓词函数。 - Rashmirathi
你想在 order.line_items 还是 order.refunds 上进行筛选? - Rashmirathi
2个回答

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_id并检查是否包含:
const itemWasRefunded = _(order.refunds)
  .flatMap("refund_line_items")
  .map("line_item_id")
  .includes(1326167752753);

1
你可以在lodash中使用somefind,在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 也可以。 - tokland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接