Ad

Lodash Filter Not Finding Value In Multidimensional Array Of Shopify Order

- 1 answer

Looking to see if an order line_item has been refunded before processing...

Here is a single order:

var order = {
  line_items: [
    {
      id: 1326167752753
    }
  ],
  refunds: [
    {
      refund_line_items: [
        {
          id: 41264152625,
          line_item_id: 1326167752753,
        }
      ]
    }
  ]
};

Trying to log out the filter results:

console.log(
  _.filter(order, {
    refunds: [
      {
        refund_line_items: [
          {
            line_item_id: 1326167752753
          }
        ]
      }
    ]
  }).length
);

I'm getting 0 on the console.

Am I using _.filter wrong in this case?

Ad

Answer

Function take needs an array (order is not an array, order.refunds is) and a predicate, not an object.

Anyway, I'd write it using Array.some:

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

Or, alternatively, getting all line_item_ids and checking inclusion:

const itemWasRefunded = _(order.refunds)
  .flatMap("refund_line_items")
  .map("line_item_id")
  .includes(1326167752753);
Ad
source: stackoverflow.com
Ad