Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
How to get Main Array with the Object when filtering a Sub array

I have this array of data, where when I filter the sub-array the orderedItems object key is only filtered not the whole data, This is my code.

const data = [
  {
    id: 6,
    orderedItems: [ { name: "Product A", vendor: 2 }, { name: "Product B", vendor: 2 }, { name: "Product B", vendor: 2 } ]
  },
  {
    id: 5,
    orderedItems: [ { name: "Product Aaa", vendor: 1 }, { name: "Product Bbb", vendor: 1 }, { name: "Product Ccc", vendor: 2 } ]
  }
];
const userId = 1;

const filteredData = data.map(({ id, orderedItems }) => {
  return {
    id: id,
    orderedItems: orderedItems.filter(({ vendor }) => vendor == userId),
  };
});

console.log(JSON.stringify(filteredData, null, 2));

Result:

[
  {
    "id": 6,
    "orderedItems": []
  },
  {
    "id": 5,
    "orderedItems": [ { "name": "Product Aaa", "vendor": 1 }, { "name": "Product Bbb", "vendor": 1 } ]
  }
]

Expected Result:

[
  {
    "id": 5,
    "orderedItems": [ { "name": "Product Aaa", "vendor": 1 }, { "name": "Product Bbb", "vendor": 1 } ]
  }
]

The filter works but only for the orderedItems object key, I wanted the id too outside of the array to be filtered too. Is there any way to do this?, If there any clarification or explanation you need please comment down below. Thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use Array#reduce to iterate over the list and in each iteration, compute the filtered orders of the current item, and in case it's not empty, add it to the accumulator with the current id:

const 
  data = [
    { id: 6, orderedItems: [ { name: "Product A", vendor: 2 }, { name: "Product B", vendor: 2 }, { name: "Product B", vendor: 2 } ] },
    { id: 5, orderedItems: [ { name: "Product Aaa", vendor: 1 }, { name: "Product Bbb", vendor: 1 }, { name: "Product Ccc", vendor: 2 } ] }
  ],
  userId = 1;

const filteredData = data.reduce((filteredItems, { id, orderedItems }) => {
  const itemFilteredOrders = orderedItems.filter(({ vendor }) => vendor == userId);
  if(itemFilteredOrders.length > 0) {
    filteredItems.push({ id, orderedItems: itemFilteredOrders });
  }
  return filteredItems;
}, []);

console.log(JSON.stringify(filteredData, null, 2));

Another way to complete your approach would be to filter the resulting list by the length of orderedItems:

const 
  data = [
    { id: 6, orderedItems: [ { name: "Product A", vendor: 2 }, { name: "Product B", vendor: 2 }, { name: "Product B", vendor: 2 } ] },
    { id: 5, orderedItems: [ { name: "Product Aaa", vendor: 1 }, { name: "Product Bbb", vendor: 1 }, { name: "Product Ccc", vendor: 2 } ] }
  ],
  userId = 1;

const filteredData = data
  .map(({ id, orderedItems }) => ({
    id,
    orderedItems: orderedItems.filter(({ vendor }) => vendor == userId)
  }))
  .filter(({ orderedItems }) => orderedItems.length > 0);

console.log(JSON.stringify(filteredData, null, 2));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use Array#reduce to go through and keep track of each match in the data array. And Array#filter to filter out the items of .orderedItems that don't pass the condition.

Full code:

const data = [ { id: 6, orderedItems: [ { name: 'Product A', vendor: 2, }, { name: 'Product B', vendor: 2, }, { name: 'Product B', vendor: 2, }, ], }, { id: 5, orderedItems: [ { name: 'Product Aaa', vendor: 1, }, { name: 'Product Bbb', vendor: 1, }, { name: 'Product Ccc', vendor: 2, }, ], }, ];

const userId = 1;

let res = data.reduce((acc, obj) => {
  let passed = obj.orderedItems.filter((subObj) => subObj.vendor === userId);
  if (passed.length) acc.push({ ...obj, orderedItems: passed });
  return acc;
}, []);

console.log(res)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You may use the method filter to select all the ids matching the userId and then proceed with your code:

const filteredData = data.filter(el => el.id === userId).map(({ id, orderedItems }) => {
  return {
    id: id,
    orderedItems: orderedItems.filter(({ vendor }) => vendor == userId),
  };
});```
   

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda