Brantley English
Brantley English

Reputation: 388

lodash filter not finding value in multidimensional array of Shopify order

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?

Upvotes: 5

Views: 1047

Answers (2)

Akrion
Akrion

Reputation: 18515

You can use some and find and do this in lodash and also easily in 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>

Upvotes: 1

tokland
tokland

Reputation: 67850

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);

Upvotes: 1

Related Questions