Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda