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

136
Visualizações
Merge values of same keys in JS

I have a dataset something like the below.

[
    {-a: '-ess. (form feminine singular nouns.)'},
    {-a: '(form the feminine singular adjectives.)'},
    {-a: '(form the second-person singular.)'}, 
    {-aba: 'first-person singular'},
    {-aba: 'third-person singular'},
    ...
]

I want to have an object that has to be converted to the format of a single object, like the below.

{
    -a: '(form the second-person singular.)', 
    -aba: 'third-person singular', 
    ... 
}

The above is a result of Object.assign({}, ...array).

But something is missing here, yep, some data has been trimmed accidentally from the original data above. This is not an desired result.

Now I have an obj that has a merged (in some way) value in the each key. The following is an example I would prefer.

{
    -a: '-ess. (form feminine singular nouns.)\n(form the feminine singular adjectives.)\n(form the second-person singular.)', 
    -aba: 'first-person singular\nthird-person singular', 
    ... 
}

So how can I achieve this? Thanks.

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

0

You can use Array.reduce(...) on your data and then loop over each object to add them to the reduced value accordingly.

Also, your original array needs some "quotes" on the object keys, otherwise it won't run:

const DATA = [
    {"-a": '-ess. (form feminine singular nouns.)'},
    {"-a": '(form the feminine singular adjectives.)'},
    {"-a": '(form the second-person singular.)'}, 
    {"-aba": 'first-person singular'},
    {"-aba": 'third-person singular'},
];

const merge = (data) => {
  // reduce the array down to a single object
  return data.reduce((acc, curr) => {
    // loop over the entries of each object
    Object.entries(curr).forEach(([key, value]) => {
      // if this key already exists, append to it with \n
      if(acc[key] != null) {
        acc[key] += `\n${value}`;

      // else, just add it as is
      } else {
        acc[key] = value;
      }
    });
    
    return acc;
  }, {});
}

console.log(merge(DATA));

about 4 years ago · Juan Pablo Isaza Relatório

0

You could do something like:

const input = [
  { "-a": '-ess. (form feminine singular nouns.)' },
  { "-a": '(form the feminine singular adjectives.)' },
  { "-a": '(form the second-person singular.)' },
  { "-aba": 'first-person singular' },
  { "-aba": 'third-person singular' }
];

// option 1: store values in array
const output1 = input.reduce((outObj, item) => {
  const [key, value] = Object.entries(item)[0];
  if (outObj[key]) {
    outObj[key].push(value);
  } else {
    outObj[key] = [value];
  }

  return outObj;
}, {});

console.log(output1);

// option 2: store values in a single string
function myFunc(arr, separator) {
  return arr.reduce((outObj, item) => {
    const [key, value] = Object.entries(item)[0];
    if (outObj[key]) {
      outObj[key] += `${separator}${value}`;
    } else {
      outObj[key] = value;
    }

    return outObj;
  }, {});
}
const output2a = myFunc(input, '\n');
const output2b = myFunc(input, ' | ');

console.log(output2a);
console.log(output2b);

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