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

256
Visualizações
Create array of multiple objects with different structure from array of objects with duplicate keys using Object.assign() in JavaScript

I have an initial array of objects in the following structure:

let sampleArray = [
  { chairperson: 'Sample person' },
  { chairperson: 'Sample person 2' },
  { arbitratorClaimant: 'Sample person 3' },
  { arbitratorRespondent: 'Sample person 4' },
  { secretary: 'Sample person 5' }
]

I am using

Object.assign({}, ...sampleArray)

to combine the array of objects into a single object, but since the object cannot have duplicate keys, it overwrites the first chairperson ('Sample person') with the second chairperson. Instead, I would like to output an array with multiple objects where objects with duplicate keys are put into the next object in the array. For instance, this is what I am looking for:

[
  {
    chairperson: 'Sample person',
    arbitratorClaimant: 'Sample person 3',
    arbitratorRespondent: 'Sample person 4',
    secretary: 'Sample person 5'
  },
  {
    chairperson: 'Sample person 2'
  }
]

Is this possible?

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

0

This is - not yet - an answer but an attempt to discuss the desired result.

How about creating a result like the following:

  {
    chairperson: ['Sample person','Sample person 2'],
    arbitratorClaimant: 'Sample person 3',
    arbitratorRespondent: 'Sample person 4',
    secretary: 'Sample person 5'
  }

Looking at your comment, maybe the following could work for you:

  {
    chairperson: 'Sample person, Sample person 2',
    arbitratorClaimant: 'Sample person 3',
    arbitratorRespondent: 'Sample person 4',
    secretary: 'Sample person 5'
  }

Instead of the ", " any other separator could be chosen for lists of multiple names

about 4 years ago · Juan Pablo Isaza Relatório

0

In this example collated is similar to @CarstenMassmann's first alternative data structure. This is quite possibly an over-involved way of doing it but the second part of the code essentially pivots (I think that's the right term) the data in collated so that it can be used for table rows.

let sampleArray = [
  { chairperson: 'Sample person' },
  { chairperson: 'Sample person 2' },
  { arbitratorClaimant: 'Sample person 3' },
  { arbitratorRespondent: 'Sample person 4' },
  { secretary: 'Sample person 5' }
];

const merge_objects = (obj1, obj2) =>
  Object.entries(obj2).reduce(
    (acc, [key, val]) =>
      Object.assign(acc, { [key]: (acc[key] ?? []).concat(val) }),
    obj1
  );

const collated = sampleArray.reduce(
  (acc, val) => merge_objects(acc, val),
  {}
);

const max_item_count = (input) =>
  Math.max(
    ...Object.values(input).map((arr) => arr.length)
  );

const get_table_rows = (input) =>
  Array
    .from({ length: max_item_count(input) })
    .map(
      (row, index) =>
        Object.fromEntries(
          Object.entries(collated)
            .map(([key, val]) => [key, collated[key][index] ?? null])
            .filter(([key, val]) => val)
        )
    );

console.log( JSON.stringify(get_table_rows(collated)) );

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