Property in javascript object

Asked

Viewed 93 times

2

How can I do a check on a array of objects where the intention would be to eliminate duplicates however, I need to add the values of a property?

Example: I have a array object:

musicas = [{nome: 'Música 1', clicks: 1}, {nome: 'Música 1', clicks: 1}]

I need to return a new array from this without repeating the songs but adding the total clicks.

Something that stayed that way:

musicas = [{nome: 'Música 1', clicks: 2}]
  • 1

    In your example you have Musica without accent in the u and with accent... are different names?

  • They’re the same thing. I forgot the accent. I’m sorry.

1 answer

3

I suggest you iterate this array and create an object at the same time. So you have in common the name of the song and add the clicks.

Something like that:

var musicas = [{nome: 'Musica 1', clicks: 1}, {nome: 'Musica 1', clicks: 1}];

var res = {};
musicas.forEach(function(musica){
    if (!res[musica.nome]) res[musica.nome] = musica; // se ainda não estiver registada
    else res[musica.nome].clicks++; // já existe, somar o click
});
console.log(JSON.stringify(res)); // {"Musica 1":{"nome":"Musica 1","clicks":2}}

// e se quiseres isso de volta numa array
var array = Object.keys(res).map(function(mus){
    return res[mus];
});

console.log(JSON.stringify(array)); // [{"nome":"Musica 1","clicks":2}]

jsFiddle: http://jsfiddle.net/Sergio_fiddle/gbw7hr1g/

Browser other questions tagged

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