Ruham
Ruham

Reputation: 759

JS filtering an Array item through a value in a nested Array

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?

Upvotes: 0

Views: 25

Answers (2)

Christian
Christian

Reputation: 7852

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

Upvotes: 1

Timur
Timur

Reputation: 2287

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)

Upvotes: 1

Related Questions