0

I can't figure out how to properly use .filter() to find an object in an Array by searching for a value in its nested Array.

I have the following data:

const orders = [
  {
    id: 1,
    items: [
      {
        itemId: "abc",
      },
      {
        itemId: "def",
      },
    ],
  },
  {
    id: 2,
    items: [
      {
        itemId: "jkl",
      },
      {
        itemId: "mno",
      },
    ],
  },
  {
    id: 3,
    items: [
      {
        itemId: "abc",
      },
      {
        itemId: "xyz",
      },
    ],
  },
];

I have the needed itemId: "abc" which I need to use to find all the objects that have items that also have the Id of "abc", so that the result is this:

 [
  {
    id: 1,
    items: [
      {
        itemId: "abc",
      },
      {
        itemId: "def",
      },
    ],
  },
  {
    id: 3,
    items: [
      {
        itemId: "abc",
      },
      {
        itemId: "xyz",
      },
    ],
  },
 ]

So far, I've tried the following:

orders &&
  orders.filter((order) => {
    return order.items.filter((item) => item.itemId === "abc");
  });

But it doesn't seem to work. What am I missing here?

1
  • 2
    In the inner function you need oder.items.some instead. Using filter inside will always result in an array, which will keep all items in the outer filter (since even an empty array is truthy) Commented Sep 14, 2021 at 19:18

2 Answers 2

1

Chris G beat me to it in the comments but he is right, you need to use order.items.some in your inner function:

const orders = [{
    id: 1,
    items: [{
        itemId: "abc",
      },
      {
        itemId: "def",
      },
    ],
  },
  {
    id: 2,
    items: [{
        itemId: "jkl",
      },
      {
        itemId: "mno",
      },
    ],
  },
  {
    id: 3,
    items: [{
        itemId: "abc",
      },
      {
        itemId: "xyz",
      },
    ],
  },
]

var ans = orders.filter((order) => {
  return order.items.some((item) => item.itemId === "abc");
});

console.log(ans)

Sign up to request clarification or add additional context in comments.

Comments

1

const orders = [{
    id: 1,
    items: [{
        itemId: "abc",
      },
      {
        itemId: "def",
      },
    ],
  },
  {
    id: 2,
    items: [{
        itemId: "jkl",
      },
      {
        itemId: "mno",
      },
    ],
  },
  {
    id: 3,
    items: [{
        itemId: "abc",
      },
      {
        itemId: "xyz",
      },
    ],
  },
];

const result = orders.filter(order =>
  order.items.find(item => item.itemId === 'abc') !== undefined
)

console.log(result);

1 Comment

Thank you for the answer! I chose the answer that included .some after a bit of a research.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.