Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

72
Vistas
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?

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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)

7 months ago · Juan Pablo Isaza Denunciar

0

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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos