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

166
Visualizações
How can I find objects with same keys values in array?

I have an array of objects that looks like this:

  const arr = [
    { type: 'type', fields: ['field1'] },
    { type: 'type2' },
    { type: 'type', fields: ['field2'] },
  ]

And I need to find objects with the same type to merge fields key in them, like this:

  const arr = [
    { type: 'type', fields: ['field1', 'field2'] },
    { type: 'type2' },
    { type: 'type', fields: ['field1', 'field2'] },
  ]

My plan was to filter through the array, but my problem is that I don't know which type will send me API, so filtering by item.type wouldn't work for me.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If that is the exact solution that you want. Following code snippet may help you.

    const arr = [
      { type: 'type', fields: ['field1']},
      { type: 'type2'},
      { type: 'type', fields: ['field2']}
    ]
    
    const modifyArr = (data) => {
      let res = [];
      arr.map((item) => {
          if(item.type == data.type){
            if(Object.keys(item).includes('fields')){
              res = res.concat(item.fields);
            }
          }
      });
      return Object.keys(data).includes('fields') ? { type: data.type, fields: res } : { type: data.type };

}

let newArr = arr.map(item => modifyArr(item));

console.log(newArr); 

This will print

[
    { type: 'type', fields: ['field1', 'field2'] },
    { type: 'type2' },
    { type: 'type', fields: ['field1', 'field2'] },
  ]
about 4 years ago · Juan Pablo Isaza Relatório

0

const arr = [{ type: 'type', fields: ['field1']}, { type: 'type2'}, { type: 'type', fields: ['field2']}];

result = arr.map(({ type }) => {
    const fields = arr.filter((o) => o.type === type).flatMap((e) => e.fields);
    return { type, ...fields[0] ? { fields } : {} };
});

console.log(result);
//[
//    {"type": "type", "fields": ["field1", "field2"]},
//    {"type": "type2"},
//    {"type": "type", "fields": ["field1", "field2"]}
//]

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