Join objects with equal values with Javascript

Asked

Viewed 375 times

0

I have an array of objects. I want to join objects that have similar values using Javascript.

const teste = [
{ Hora: '23:49:08.277',
    CodigoDoPiloto: '038',
    Piloto: 'F.MASSA',
    Volta: '1\t\t',
    TempoDaVolta: '1:02.852',
    VelocidadeMediaDaVolta: '44,275\r' },
  { Hora: '23:49:10.858',
    CodigoDoPiloto: '033',
    Piloto: 'R.BARRICHELLO',
    Volta: '1\t\t',
    TempoDaVolta: '1:04.352',
    VelocidadeMediaDaVolta: '43,243\r' },
  { Hora: '23:50:11.447',
    CodigoDoPiloto: '038',
    Piloto: 'F.MASSA',
    Volta: '2\t\t',
    TempoDaVolta: '1:03.170',
    VelocidadeMediaDaVolta: '44,053\r' }

]

I want it to stay this way:

newTeste = [
   {Hora: '23:49:08.277',
    CodigoDoPiloto: '038',
    Piloto: 'F.MASSA',
    Volta: '1\t\t',
    TempoDaVolta: '1:02.852',
    VelocidadeMediaDaVolta: '44,275\r',
  **Hora: '23:50:11.447',
    Volta: '2\t\t',
    TempoDaVolta: '1:03.170',
    VelocidadeMediaDaVolta: '44,053\r'}**,

   { Hora: '23:49:10.858',
    CodigoDoPiloto: '033',
    Piloto: 'R.BARRICHELLO',
    Volta: '1\t\t',
    TempoDaVolta: '1:04.352',
    VelocidadeMediaDaVolta: '43,243\r' }
]

I want to do it dynamically:

if(test. Pilot === test.Pilot){ ???? }

  • You want to unite all the values are equal or only if the pilots are the same?

  • Only if the riders are equal. If equal add the other elements in the same object.

  • 1

    But in that case there will be data loss, since an object cannot have two equal keys, even if with different values. For example, in Javascript, this is invalid: { a: 25, b: 50 }. Moreover, the result you expect (according to the question) is incorrect taking into account this JS standard, since objects share more than one property with equal keys.

  • I get it, thank you.

  • Does the answer answer answer your question? If so, please consider accepting it.

1 answer

1

As mentioned in the comments, in Javascript, you cannot create an object that has two properties that share the same key. For example:

console.log({
  name: 'Unknown',
  name: 'Luiz Felipe',
  age: 16
});

// Note que a chave `name` que continha "Unknown" sumiu.

If you do, no error will be released, but you will lose data silently, so that only the last set key will be kept.

So unless you desire one output different, the one mentioned in the question is impossible to be reached using Javascript.

Be sure to find out more about javascript objects.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.